Page methods in ASP.Net

In my previous post I mentioned about accessing server side controls in Java script using ASP.Net Ajax API. That functionality is can be combine with the Page methods feature, for simple Ajax calls without update panel control. You can create a Page method by adding a [WebMethod] attribute in the declaration. For this you need to import System.Web.Servicesnamespace. The function should be public static, otherwise it will not work.
C# Code

[System.Web.Services.WebMethod()]
public static string HelloWorld()
{
return ("Hello World");
}

And in the script manager control, you need to set the EnablePageMethodsproperty to True. Thats it you created a Page Method. You can access it in the Javascript like

Javascript code

function invokeHelloWorld()
{
PageMethods.HelloWorld(HelloWorldCallback); //Invoking the Page method, with callback function as the parameter.
}
function HelloWorldCallback(res)
{
alert(res);
}

You need to pass the Callback function as the last parameter, when you call the Page methods. You can pass the other parameters before the callback function. In the callback function you will the results from the specific operation.

Note: Page methods is Public static so we will not able to access the Page and Control objects from the function.

This is my 100th post :) Thanks for you support , cooperation, and the valuable comments.

This entry was posted in .Net, .Net 3.0 / 3.5, ASP.Net, Javascript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>