从JS/AJAX调用用户控件静态方法报错NotFound,求解决方法
解决用户控件中WebMethod无法被AJAX调用的问题
哈哈,这个问题我太熟了!之前也踩过同样的坑,ASP.NET里用户控件(.ascx)的WebMethod确实没法直接通过AJAX调用,原因很简单——用户控件不是独立的HTTP端点,ASP.NET的请求管道根本不会处理对.ascx文件的直接请求,所以你才会拿到NotFound错误。下面给你几个实用的解决方案:
方案一:把WebMethod移到宿主WebForm页面
最直接的办法就是把静态方法从用户控件搬到它所在的.aspx页面里,然后修改AJAX的请求地址:
后台代码(YourPage.aspx.cs)
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string GetNameFromCodeBehind(string name) { return "Hello from Code-Behind, " + name; }
修改后的AJAX代码
$.ajax({ type: "POST", url: "YourPage.aspx/GetNameFromCodeBehind", // 改成宿主页面的路径 data: JSON.stringify({ name: "Anton" }), contentType: "application/json; charset=utf-8", dataType: "json", processData: true, // 注意这里是大写D,你之前写的processdata会报错 success: function (data) { alert(data.d); }, error: function (e) { alert(e.statusText) } });
方案二:在宿主页面写代理方法调用用户控件的方法
如果不想把方法移出用户控件,可以在.aspx页面写一个“代理”WebMethod,间接调用用户控件里的静态方法:
用户控件后台代码(MyUserControl.ascx.cs)
// 保持原方法不变,注意要设为public static [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string GetNameFromCodeBehind(string name) { return "Hello from Code-Behind, " + name; }
宿主页面后台代码(YourPage.aspx.cs)
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string ProxyGetName(string name) { // 直接调用用户控件的静态方法 return MyUserControl.GetNameFromCodeBehind(name); }
对应的AJAX代码
$.ajax({ type: "POST", url: "YourPage.aspx/ProxyGetName", // 请求代理方法 data: JSON.stringify({ name: "Anton" }), contentType: "application/json; charset=utf-8", dataType: "json", processData: true, success: function (data) { alert(data.d); }, error: function (e) { alert(e.statusText) } });
额外提醒
你原来的AJAX代码里有个小错误:processdata应该写成processData(JavaScript是大小写敏感的),这个细节也可能导致请求异常,记得修正哦!
内容的提问来源于stack exchange,提问作者Nani
相关产品推荐
相关产品推荐

