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]You call it in JavaScript with:
public static string HelloWorld()
{
return "Hello World!";
}
PageMethods.HelloWorld(MyCallbackHandler);And natch you have to provide that callback handler function e.g.
function MyCallbackHandler(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.
{
alert(Result);
}
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.