gru*_*ber 39 c# asp.net jquery ascx webmethod
是否可以将WebMethod放在ascx.cs文件中(对于UserControl),然后从客户端jQuery代码调用它?
出于某些原因,我无法将WebMethod代码放在.asmx或.aspx文件中.
示例:在ArticleList.ascx.cs中,我有以下代码:
[WebMethod]
public static string HelloWorld()
{
return "helloWorld";
}
Run Code Online (Sandbox Code Playgroud)
在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);
}
});
Run Code Online (Sandbox Code Playgroud)
而firebug的错误是:
<html>
<head>
<title>This type of page is not served.</title>
Run Code Online (Sandbox Code Playgroud)
如何从客户端jQuery代码中成功调用服务器端WebMethod?
Hom*_*mam 31
WebMethod应该是静态的.因此,您可以将其放在用户控件中,并在页面中添加一个方法来调用它.
编辑:
您无法通过用户控件调用Web方法,因为它将自动在页面内呈现.
您在用户控件中使用的Web方法:
public static string HelloWorld()
{
return "helloWOrld";
}
Run Code Online (Sandbox Code Playgroud)
在Page类中添加web方法:
[WebMethod]
public static string HelloWorld()
{
return ArticleList.HelloWorld(); // call the method which
// exists in the user control
}
Run Code Online (Sandbox Code Playgroud)
Joe*_*nos 11
你的方法需要在.aspx中(或者我认为.ashx或.asmx也可以).由于它实际上是对Web服务器进行新调用,因此IIS必须处理该请求,并且IIS不会响应对.ascx文件的调用.
您不能使用Jquery Ajax直接在用户控件中调用方法.
您可以尝试以下方法之一:
将URL设置为PageName.aspx?Method=YourMethod或可能添加一些其他限制,以便您知道哪个用户控件应该执行该方法.然后在您的用户控件中,您可以检查查询字符串中是否存在限制,并执行给定的方法.
如果需要执行异步操作,可以使用客户端回调来执行某些方法.在页面的GetCallbackResult中,您可以找到导致回调的控件,并将请求及其参数传递给控件.