ASP.NET Page Methods and jQuery

ASP.NET has a very nice architecture to pack all backend AJAX methods and jQuery in the same ASPX file.
Lets say you have a simple Page Method like below. You need to include the “System.Web.Services” and declare your method as WebMethod.

 [WebMethod] public static int Sum(int a, int b) { return a + b; } 

Make sure your page method is static

The JQuery way of calling this function would be something similar to this.

 $(document).ready(function () { $("#btnSum").click(function () { $.ajax({ type: "POST", url: "Default.aspx/Sum", data: "{'a':" + $("#txtA").val() + ",'b':" + $("#txtB").val() + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { $("#lblOutput").html(result.d); } }); }); }); 

In Line 5, I am assuming the file name is Default.aspx and thus you call Default.aspx/Sum. If you notice on line 10, the result is enclosed in a json object called “d”. So to unpack you would have to call result.d

HTML Form would be something like this

 <form id="form1" runat="server"> <div> A: <input type="text" id="txtA" /> B: <input type="text" id="txtB"/> <input type="button" value="Sum" id="btnSum"/> <div id="lblOutput"></div> </div> </form> 

You can download the file below

Page Methods Sample

By: bozena on: