我有以下web方法,它没有击中webmethod上设置的断点
CS:
[WebMethod] public static string search() { return "worked"; }
ASPX:
function search() { $.ajax({ type: "POST",url: "ProcessAudit/req_brws.aspx/search",data: "{}",contentType: "application/json; charset=utf-8",dataType: "json",success: function (msg) { alert(msg) } }); } <button id = "btnSearch" onclick = "search()" >Search</button>
解决方法
确保您已经在ScriptManager元素中启用了页面方法:
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
并且您已经通过在onclick处理程序中返回false来取消按钮的默认操作,否则页面执行完整的回发,并且您的AJAX调用可能永远不会有时间完成。这是一个完整的工作示例:
<%@ Page Language="C#" %> <script type="text/c#" runat="server"> [System.Web.Services.WebMethod] public static string search() { return "worked"; } </script> <!DOCTYPE html> <html> <head id="Head1" runat="server"> <title></title> </head> <body> <form id="Form1" runat="server"> <asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" /> <button id="btnSearch" onclick="search(); return false;" >Search</button> </form> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript"> function search() { $.ajax({ type: 'POST',url: '<%= ResolveUrl("~/default.aspx/search") %>',data: '{ }',contentType: 'application/json; charset=utf-8',dataType: 'json',success: function (msg) { alert(msg.d) } }); } </script> </body> </html>
另一种可能性是不引人注意地订阅点击处理程序:
<button id="btnSearch">Search</button>
然后在一个单独的javascript文件中:
$('#btnSearch').click(function() { $.ajax({ type: 'POST',success: function (msg) { alert(msg.d) } }); return false; });
您可能还会注意到成功回调中使用的msg.d属性,ASP.NET用于将整个响应包含在内,以及ResolveUrl方法的正确生成url到page方法的用法,而不是对其进行硬编码。