Calling Methods Present In The Code-behind File Using ScriptManager
In my previous post we saw how to call a web service from the java script .
So is it necessary to have a web service for just calling a single web method present in it. It requires over head in hosting this particular web service. So it would be nice if we can have that web method in our code behind file itself.
So in this post we will see the process involved in calling the methods present in the code behind file from java script code.
What is Page Methods
Page Methods is ajax allows us to call the methods present in the code behind file.
1.Create an empty web site application in the visual studio.
2.Add an aspx page to the project created above.
3. Add a method in the aspx.cs file(code behind file).
5.So in order to make a method as web method we should include “using System.Web.Services;” namespace.
6.The methods we are going to call from the java script should be declared as static and it is a must.
So in my case i am adding a method TestWebService with single parameter.
Now let us make a move the aspx page.
1.So in order to call the web method declared in the code behind file we should include the control to the aspx page.
<asp:ScriptManager ID="scriptmanager1" runat=server EnablePageMethods="true"> </asp:ScriptManager>
3.By adding the above tag we got rights to call the method present in the code behind file. Now add the java script code to the aspx page that involves the call to the code behind file.
So in the above code we are having a method called “callCodeBehindMethod” in which we are calling the code behind method TestCodeBehind(). Actually this particular method in aspx.cs file accepts single parameter of type string. But in this method we are passing 3 parameters. one is string that the method actually accepts and the other 2 that is onSuccess and onFailure are call back functions that are executed either if the request is successful or failure. Also we can have an optional parameter “userContext” to this method.
The other major thing in this method “callCodeBehindMethod” is PageMethods. In order to call the method we should use this “PageMethods” attribute. If we are calling a web service instead of Pagemethods we are supposed to use Webservice class name. As we are calling the code behind file we should use PageMethods.
Code for entire aspx page.
Drawbacks of PageMethods
1. The major drawback of page methods is we cannot access .net controls like textbox ,gridview and other control in the page method that is declared in the code behind file.
For example we are having an textbox in the aspx page and we can access this in the code behind file but not in the TestCodeBehind() method which is declared as web method and also as static.
The reason behind this is inorder to make a method as page method it is compulsory to declare it as webmethod and static. And it is a basic oops principle that we cannot access non static methods and properties inside a static method.