如何调用一个ASP.NET的WebMethod在用户控件(的.ascx) [英] How to call an ASP.NET WebMethod in a UserControl (.ascx)
问题描述
是否有可能放置在ascx.cs文件一个WebMethod(对于用户控件),然后从客户端的jQuery code称呼呢?
Is it possible to place a WebMethod in an ascx.cs file (for a UserControl) and then call it from client-side jQuery code?
对于一些原因,我不能把将WebMethod code在的.asmx或.aspx文件。
For some reasons I can't place the WebMethod code in an .asmx or .aspx file.
例如:在ArticleList.ascx.cs我有以下的code:
Example: In ArticleList.ascx.cs I have the following code:
[WebMethod]
public static string HelloWorld()
{
return "helloWorld";
}
在ArticleList.ascx文件中,有我在调用的WebMethod如下:
In ArticleList.ascx file there I have the call to the WebMethod as follows:
$.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);
}
});
和来自萤火虫的错误是:
and the error from firebug is:
<html>
<head>
<title>This type of page is not served.</title>
如何能成功地我从我的客户端的jQuery code调用服务器端的WebMethod?
推荐答案
的WebMethod应该是静态的。所以,你可以把它放在用户控件,并在页面中添加一个方法来调用它。
WebMethod should be static. So, You can put it in the user control and add a method in the page to call it.
编辑:
您不能调用通过用户控件的Web方法,因为它会在页面内自动呈现。
You can not call a web method through a user control because it'll be automatically rendered inside the page.
您在用户控件有Web方法:
The web method which you have in the user control:
public static string HelloWorld()
{
return "helloWOrld";
}
在页面类中添加Web方法:
In the Page class add the web method:
[WebMethod]
public static string HelloWorld()
{
return ArticleList.HelloWorld(); // call the method which
// exists in the user control
}
这篇关于如何调用一个ASP.NET的WebMethod在用户控件(的.ascx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!