by Stian

Call ASP.NET AJAX page methods using jQuery

If you are used to working with MVC.NET and jQuery you might not want to start playing with the ScriptManager when you go back to writing an ASP.NET Web application again. Calling WebMethods using the ScriptManager will automatically add 100kb of Javascript to your page and will add three extra http requests per call! Of course, it is very simple to use, but so is the jQuery way as well, so if you are used to calling your actions directly with .ajax(), there is no reason not to .

To call ASP.NET page methods directly from jQuery without the need of a ScriptManager in your page, use the following:

Your jQuery code

   1:  var params = '{"firstname":"' + $("#firstname").val() + 
   2:               '", "lastname":"' + $("#lastname").val() + '"}';
   3:  $.ajax({
   4:      type: "POST",
   5:       url: "Default.aspx/SavePerson",
   6:       data: params,
   7:        contentType: "application/json; charset=utf-8",
   8:        dataType: "json",
   9:        success: function (msg) {
  10:            alert(msg.d)                      
  11:        }
  12:  });

Your serverside code

   1:  [WebMethod]
   2:  public static string SavePerson(string firstname, string lastename)
   3:  {
   4:      //do saving or wheatever
   5:      return "Some message back to client";
   6:  }

 

If you’re already using the ScriptManager for other purposes, there’s no harm in using its JavaScript proxy to call your page methods. However, if you aren’t using a ScriptManager or have already included jQuery on your page, I think it makes sense to use the more efficient jQuery method.