How to access page methods from JQuery


Most of the time to make web page ajax, developers were using UpdatePanel with Script Manager and sometimes (most of the time in my experience) the update panel will affect the performance of the Page. One of the project I used script manager and Pagemethods for the ajax implementation. The current project I am working, I got some weired error from Script Manager, the error was Sys.Net was not defined. I tried various solutions to fix this but it was throwing the same exception :( and the funny thing, it was working perfectly in one page. :) So I thought doing the same thing with JQuery, and here is the code snippet, which will help to access page methods using JQuery.

Here is my page method.

public static int Add(int a, int b)
    return a + b;

And here is my javascript code to access PageMethod

var dataToPost = { 'a': '10', 'b': '20' };
    type: "POST",
    url: "chat.aspx/Add",
    data: JSON.stringify(dataToPost),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (res) { alert("Result :" + res.d); },
    error: function (res) {
        alert("An exception occured:" 
    + res.statusText); }

The type parameter defines the type of HTTP operation(GET / POST), url is the location to post/get data, data is the list of the parameters, the page method expects. You don’t need to use stringify method, but I found some problem without using it. The success and error are event handlers, which will fire when request was successful and server is returning some value, or if there is any error.

Happy Programming :)

Anuraj is currently working as Technical Lead. He is a regular speaker on Technology events. He has more than 11+ years experience with Microsoft.Net Technologies.

Facebook Twitter LinkedIn Google+ 

  • Naveen

    Actually you can omit declaring dataType at all. Also contentType could be shortened to just contentType: “application/json;”

    Source: Save yourself some typing when you call ASP.NET services

    • Anuraj P

      @Naveen thanks :)