在ASP.NET WebForms中使用jQuery调用'WebMethod'

时间:2011-08-03 14:57:15

标签: jquery asp.net ajax webforms webmethod

我在以下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>

3 个答案:

答案 0 :(得分:28)

确保您已在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',
        url: '<%= ResolveUrl("~/default.aspx/search") %>',
        data: '{ }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert(msg.d)
        }
    });
    return false;
});

您可能还会注意到成功回调中msg.d属性的使用,ASP.NET使用该回调来包装整个响应,以及使用ResolveUrl方法来正确生成URL到页面方法而不是硬编码。

答案 1 :(得分:5)

更优化的通话将是

function search() {
    $.ajax({
        type: "POST",
        url: '<%= ResolveUrl("~/ProcessAudit/req_brws.aspx/search") %>',
        data: "{}",
        contentType: "application/json",
        success: function (msg) {
            msg = msg.hasOwnProperty("d") ? msg.d : msg;
            alert(msg);
        }
    });
}

根本不需要提供asp:ScriptManager

资源:http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

答案 2 :(得分:1)

您当前的按钮会导致完整的回发。 只需添加一个类型=&#34;按钮&#34;到你的按钮以避免这种情况。

 <button id = "btnSearch" type="button" onclick = "search()" >Search</button>

-Shazzam哟