Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a 'WebMethod' with jQuery in ASP.NET WebForms

I've set a breakpoint in the following WebMethod but I'm never hitting the breakpoint.

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>
like image 247
marknery Avatar asked Aug 03 '11 14:08

marknery


People also ask

How do I call a WebMethod URL?

click(function () { var name = $('#name'). val(); /// alert("The btn was clicked."); jQuery. ajax({ url: 'test. aspx/GetData', type: "POST", dataType: "json", // data: "{'name': '" + name + "'}", contentType: "application/json; charset=utf-8", success: function (data) { alert(JSON.

How do you call webmethods?

you need to JSON. stringify the data parameter before sending it. Show activity on this post. From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.


3 Answers

Make sure that you have enabled page methods in your ScriptManager element:

<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />

and that you have canceled the default action of the button by returning false inside the onclick handler, otherwise the page performs a full postback and your AJAX call might never have the time to finish. Here's a full working example:

<%@ 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>

Another possibility is to subscribe to the click handler unobtrusively:

<button id="btnSearch">Search</button>

and then inside a separate javascript file:

$('#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;
});

You might also notice the usage of the msg.d property inside the success callback which ASP.NET uses to wrap the entire response into as well as the usage of the ResolveUrl method to properly generate the url to the page method instead of hardcoding it.

like image 60
Darin Dimitrov Avatar answered Oct 05 '22 23:10

Darin Dimitrov


A more optimised call will be

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);
        }
    });
}

No need to provide a asp:ScriptManager at all.

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

like image 7
naveen Avatar answered Oct 05 '22 23:10

naveen


Your current button is causing a full postback. Simply add a type="button" to your button to avoid this.

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

-Shazzam yo

like image 4
HeavyMerlin Avatar answered Oct 05 '22 23:10

HeavyMerlin