PageMethods In ASP.NET AJAX

We all come across to such situation where you need to call server side code from JavaScript, not using jQuery AJAX though, without allowing form to post back to it. Further posting was required to capture data and save it into the database as well.
Page Methods is a mechanism introduced in ASP.Net 2.0 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. 
Here are few easy steps we will be doing to get this done:
1. Create a JavaScript method. I will name it “CallServereMethod”. Here is the code:

function CallServereMethod()
{
            var OrderID = document.getElementById(“txtOrderID.Text”).Text;
PageMethods.PlaceOrder(OrderID,onSucceed, onError);

this.myform.submit();
}

function onSucceed(result, currentContext, methodName)
{
            // Do Something with “result”        
}
function onError(result, currentContext, methodName)
{      
            // Do Something
}


2. PageMethods is something most of you might be familiar with or even heard of. We need to set “EnablePageMethods” to true in ScriptManager.

<asp:ScriptManager ID=”sm” runat=”server” EnablePageMethods=”true” />


3. Now we will define our server side method which actually does the trick, saving record in database in my case:
[WebMethod]
public static void PlaceOrder (string pOrderID)
{
If(ValidateOrder(pOrderID))
{
          ApproveOrder();
}

}

We must add method attribute [WebMethod] before we define our method else the method call will fail from JavaScript.


4. Finally, we need to add an attribute to our form; here my form id is “myform”:


this.myform.Attributes.Add(“onsubmit”, “CallServereMethod ()”);


This will trigger our JavaScript method at the form is submitted. This line can be added in Page_Load event handler.


The ScriptManager renders the java script to access the web methods when the EnabledPageMethods is set to “True”.  An JavaScript object Page Methods is created using which we can access the web methods of the page.    
In order to call web methods using PageMethods object we should add a function for Successful Page method call and a function for UnSuccessful Page method call as seen in our sample above. These functions can be treated as Callback functions.

Advantages
·         This approach is easier and the code is shorter and reliable.
·         It provides greater compatibility since it is easy to change fast.
·         Less work for developer to write client script and a server method.
·         Page parameters become strongly typed and automatically validated.
·         You don't have to parse and convert parameters by yourself. In ASP.NET, parameters passed on URLs are available through Request.QueryString, only as strings.
·         No need to look at a target page's code to know how to call it. No need for separate documentation about ways to call a page.
·         Page parameters are automatically validated and become strongly typed.
·         As we don’t to post entire viewstate of the page using Page Methods we achieve the bandwidth benefits.

Key Points to Remember
·         The Page Method should be static using the attribute [WebMethod].
·         The Page Method can be in the code behind file of the page and in aspx file as well.
·         The EnablePageMethods property of the script manger should be marked as “True”.
·         The call back methods are mandatory to receive the processed result on the client side.
·         Page Methods don’t support all the datatypes to return to client.
·         We can access the Session. Application and Cache variables using Page Methods.

Comments

Popular posts from this blog

Data Bound Controls in ASP.Net - Part 4 (FormView and DetailsView controls)

ASP.net: HttpHandlers

The Clickjacking attack and X-Frame-Options