PageMethods In ASP.NET AJAX

Page Methods is a new mechanism in ASP.Net application where the server code cab be bound to Asp.Net pages.  It is an easy way to communicate asynchronously with the server using Asp.Net Ajax technologies. It’s an alternate way to call the page which is reliable and low risk.  In a nutshell, it is used to expose the web methods to the client script.


Sample Application Demonstrating Page Methods

  • To enable Page methods we need to drag a ScriptManager control to the page and mark the EnablePageMethods to True.

   1: <asp:ScriptManager ID="ScriptManager1" runat="server"   

   2:       EnablePageMethods="True">

   3: </asp:ScriptManager>

  • Go the Code behind file of the page and add a static method and mark them as WebMethod. Lets Say the method name is GetPageMethod which returns a status value.
   1: [System.Web.Services.WebMethod]        

   2: public static string GetPageMethod()

   3: {

   4:       return "Welcome PageMethods";

   5: }

  • Now that the method is exposed add a button control and call a client script which accesses the Webmethods of the page.
   1: <asp:Button ID="Button1" runat="server" Text="Call Page Methods"  

   2:       OnClientClick="return fun()"/>

  • In javascript function we can use PageMethods object to call the WebMethod of the page.
       1: function fun()

       2: {    

       3:      PageMethods.updateProduct(GetPageMethod,OnSucceeded,OnError);    

       4: }


       6: function OnSucceeded(result, userContext, methodName) 

       7: {

       8:     if (methodName == "GetPageMethod")

       9:     {

      10:   alert(result);

      11:     }

      12: }


      14: function OnError(result,userContext,methodName)

      15: {

      16:     if(methodName == "GetPageMethod")

      17:     {

      18:         IsError = 1;

      19:     }

      20: }


  • Now run the application and check the result which shows the alert box with value “Welcome PageMethods”. The sample application calls the webmethods of the page using client script without full page cycle.

One thought on “PageMethods In ASP.NET AJAX

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s