【发布时间】:2011-08-04 00:52:26
【问题描述】:
是否可以将 WebMethod 放在 ascx.cs 文件中(对于 UserControl),然后从客户端 jQuery 代码中调用它?
由于某些原因,我无法将 WebMethod 代码放在 .asmx 或 .aspx 文件中。
示例:在 ArticleList.ascx.cs 我有以下代码:
[WebMethod]
public static string HelloWorld()
{
return "helloWorld";
}
在 ArticleList.ascx 文件中,我对 WebMethod 的调用如下:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "ArticleList.ascx/HelloWorld",
success: function(msg) {
alert(msg);
}
});
萤火虫的错误是:
<html>
<head>
<title>This type of page is not served.</title>
如何从客户端 jQuery 代码成功调用服务器端 WebMethod?
【问题讨论】:
-
我们可以看一些代码吗? Web 用户控件的作用类似于母版页。一旦页面呈现给浏览器,一切就好像它是一个页面一样开始。
-
啊,我明白你在做什么了。当我在 asp.net 中使用 Ajax 时,我创建了一个 web 服务文件。它具有 .asmx 扩展名。如果你使用它,它是存储所有 ajax 方法的好地方。
-
由于某些原因,我无法将此代码放在 asmx 或 aspx 文件中。
-
This question 似乎相关,但并不完全相同。
标签: c# jquery asp.net webmethod ascx