On the topic of Microsoft ASP.NET AJAX, a particularly overlooked and, for its simplicity, useful feature is the ASP.NET WebMethod. A WebMethod is simply a server side ASP.NET page method that can be called by client script. Not only is the method integrated with your page code (convenient for small applications) but the ASP.NET compiler automatically adds client-side methods that take care of the AJAX request, JSON encoding and, to a degree, data type conversion. Sure, you could do this using a web service and XmlHttpRequest - but this is a quick-and-easy way of AJAX-enabling standard web form pages.
The handy thing about the WebMethod is that, assuming ASP.NET 3.5 is setup in your web.config, the development requirement and learning curve are minimal. In short, to create a WebMethod you must do three things:
- Import the System.Web.Services namespace on your page.
- Add the [WebMethod] attribute to a static page method.
- Add a ScriptManager control with the EnablePageMethods property set to true.
After that, it's just a matter of calling the function from JavaScript, which can be accessed as a client-side method off a PageMethods object that ASP.NET automatically generates. This method automatically includes overloads for two optional parameters, a success and fail function. So, for example, if your server method looked like:
[WebMethod]
public static string GetAvatar(string username) {
...
}
Then your client-script might simply call:
PageMethods.GetAvatar('Levi', success);
were success is the name of a function that takes a single parameter representing the output returned from the server method (in this case expected as a string - although it could be a bool, int or other scalar value type). Further, if you monitor your Firebug console, you'll notice that the method is exposed as a REST-like interface with the method name being accessible as part of the page URL and the parameter POSTed as a JSON object thus allowing this to be optionally called from other pages.
Certainly the WebMethod is hardly a replacement for more sophisticated RESTful APIs in larger applications. Nor is it competitive with the IScriptControl interface which allows AJAX methods to be fitted into server controls. For day-to-day development, however, it makes adding AJAX features to a small web application easy - and, more importantly, keeps the code centralized and easy to maintain.
tags: WebMethod, AJAX, ASP.NET, C#, JavaScript, Microsoft