Everyone using ajax.net will be familiar with the updatepanels. In addition another well known way of utilizing the rich ajax.net library is calling web service methods or methods from the code behind file from the client side. Recently i came across a situation in my project where i wanted to call methods from code behind (i have been using updatepanels but in some situation all i was doing was getting few values from the db and i felt not using the updatepanel would be a better option rather calling the my code behind function using pagemethods feature would be more appropriate). Though there is a good deal of information on the internet on update panels and calling web services i found it difficult to reach a good enough article showing me how to call a function from the codebehind file. Finally though :-) i was able to call the code behind function. i am going to demonstrate the same in this blog.
Before starting let me indicate there could be many reasons for calling code behind methods from client side using ajax.net .....in my case i wanted to use existing functionality in my code behind and we were not using any webservices .
Here i am going to demonstrate a simple application that calls a code behind method
to start first we create an ajax enabled website. Then in our page we add the heart of ajax.net -- the ScriptManager control and set the EnablePageMethods property as true
<ajax:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
We also place a div and input buttons on our form
<input type="button" value="Call Page Method With No Parameters" onclick="CallPageMethod()" />
<input type="button" value="Call Page Method With Parameters" onclick="CallParametersPageMethod()" />
As the text indicates on call a function without parameters and the other calls a function having parametersThe code behind function are as below
public static string MyFirstPageMethod()
return "Welcome to the world of AJAX.NET " ;
public static string MyFirstParameterPageMethod(String strVal)
return "Welcome to the world of AJAX.NET , the value you passed is : " + strVal ;
To call a page method it must be static and you have to mark it with the WebMethod attribute. The first function doesnot takes parameter while the second function takes a string value as parameter. both return a string value.
PageMethods.MyFirstParameterPageMethod("This is a Demo",onSucceeded,onFailed);
alert("An error occurred")
The CallPageMethod method calls the parameterless function MyFirstPageMethod from codebehind and the CallParametersPageMethod calls the code behind function MyFirstParameterPageMethod and passes a string as parameter
We call the codebehind method as PageMethods.MethodName();
In case the code behind function has no parameters then we pass the onSucceeded and OnFailed parameters only.
The return value is displayed in the div.
I have attached the complete code of this.
Hope this is helpful to you all.