5 Jul 2007

Of ASP.NET Ajax PageMethods and Men

[11 Feb 2010] Since I wrote this, I would use the following method to call PageMethods from JavaScript: http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/





I've been having fun with ad-hoc AJAX calls using ASP.NET Ajax recently. And when I say fun, I mean in the sense of "no fun at all". Partly due to crap documentation and a million blog posts with example code based on obsolete beta Atlas functionality.

So here's a little tipfest about PageMethods.

You can call .NET methods of your ASPX page via client-side Javascript. But first you have to jump through some hoops:

1. The ASP.NET Ajax ScriptManager control in your .aspx or MasterPage needs to be set with: EnablePageMethods="true"

2. The .NET method you wish to expose to AJAX must be public and static and marked with the [System.Web.Services.WebMethod] attribute

Once that's done you can call your method from javascript after the AJAX script libraries have finished loading (with Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded() or something).

So, given a WebMethod like so:
[WebMethod]
public static string HelloWorld()
{
return "Hello World!";
}
You call it in JavaScript with:
PageMethods.HelloWorld(MyCallbackHandler);
And natch you have to provide that callback handler function e.g.
function MyCallbackHandler(Result)
{
alert(Result);
}
That's right my friends, the PageMethod takes the original argument list, plus one extra for the mandatory callback function, and then there are some optional extra callback arguments you can provide regarding error handling etc. Check out the docs for more info.

One extra thing to note - I read a few blogs bitching that the WebMethod had to be declared in the .aspx page, not the code-behind code. That's not true anymore, it works fine both ways.
If I helped you out today, you can buy me a beer below. Cheers!