ASP.NET has all kinds of fancy features for out-of-band ajax communication. There's web services, script methods, page methods and what not. I was looking for an easier, low profile method that will also work without the Microsoft's AJAX framework and doesn't require proxy generation by ScriptHandlerFactory. The goal is to be able to do some AJAX stuff with a jQuery.
MVC leads the way
So, looking at the MVC Beta, I noticed there's a JsonResult class. The gut of the class does nothing more than this:
$.getJSON("Default.aspx", dataReady);This will trigger a post to the ASP.NET page. The dataReady function will be invoked when the request returns. But how do we know whether to return JSON data or normal web content? One option is to append a parameter to the url (for example ajax=true). A nicer solution is to check the headers. jQuery will set the Accept header to indicate it expects a JSON result:
Now, by overriding the Render method in the page it's relatively easy to handle both the web requests and the ajax requests:
Please note that this is just a proof of concept; in a real life application you should impose all kinds of security measures before responding to an AJAX request. You may also want to split the page and the handling of the AJAX callbacks into separate classes. Handling the AJAX request through an IHttpHandler a lot more efficient.