Search code examples
jqueryasp.netwebmethod

jQuery don't call ASP.NET WebMethod


I know there are plenty of questions like this one but I just can't solve my problem with those answers.

I have basic page and on it:

<body>
<form id="form1" runat="server">
    <div id="Result">
        <asp:ScriptManager ID="ScriptManager1"
            EnableScriptGlobalization="true"
            EnableScriptLocalization="true"
            EnablePageMethods="true"
            EnablePartialRendering="true" runat="server" />

        <script type="text/javascript">

            $(document).ready(function () {
                $("#txtSearch").bind("change", search);

            });

            function test() {
                alert("asdadadaads");
            }

            function search() {
                $.ajax({
                    type: "POST",
                    url: "~/Search.aspx/GetRegion",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        alert(msg.d)
                    }
                });
            }
        </script>

        <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    </div>
</form>

I am able to call test function and it shows alert. Also in Firebug I see that search() function is also called but I can't step into my code behind WebMethod.

WebMethod is like this:

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static void GetRegion()
    {
        SearchService.Service1 client = new Service1();

    }

I am getting crazy with this so thanks if you can help :)


Solution

    1. Remove ~ from url in $.ajax request.
    2. No need of ScriptManager// Won't matter even if you not changed
    3. Put search() function outside the (document).ready() function.// Won't matter even if you didn't change
    4. Change $("#txtSearch").bind("change", search); => $("#txtSearch").change(search);// Won't matter even if you didn't change
    5. Also make sure same id txtSearch rendered (may not render same if master pages are used). You can use <%:txtSeacrh.ClientId%> to get clientId in HTML markup.

    There is no need to use bind function if txtSearch exists in the DOM while the page loads.Also jQuery prefers to use on function instead.

    $( "#txtSearch" ).on( "change", search);
    

    jsFiddle