是否可以将 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);
}
});
firebug 的错误是:
<html>
<head>
<title>This type of page is not served.</title>
如何从我的客户端 jQuery 代码成功调用服务器端 WebMethod?
最佳答案
WebMethod 应该是静态的。所以,你可以把它放在用户控件中,然后在页面中添加一个方法来调用它。
编辑:
您不能通过用户控件调用网络方法,因为它会在页面内自动呈现。
用户控件中的 web 方法:
public static string HelloWorld()
{
return "helloWOrld";
}
在 Page 类中添加 web 方法:
[WebMethod]
public static string HelloWorld()
{
return ArticleList.HelloWorld(); // call the method which
// exists in the user control
}
关于c# - 如何在 UserControl (.ascx) 中调用 ASP.NET WebMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5638184/