Most people who first start toying around with ASP.NET AJAX experience the coolness of using the UpdatePanel in their projects to cleanly update portions of their page. The end result is cool, the ease by which you can get at the result is cool and, well, everything about the experience is pretty cool.
However, the ease and coolness factor come at a price - effeciency and finely grained control. For, I would think, about 70% of your development needs this is okay – given that most of what you’ll be using AJAX for is simple region refreshes, etc. However, there are those situations where you might need a bit more from your AJAX framework, and if that’s the case, you should have a look at the WebRequest (Sys.Net.WebRequest) class.
Sys.Net.WebRequest is a client-side class (therefore written in ECMA script) that is the foundation for all asynchronous web requests that occur in ASP.NET AJAX (the UpdatePanel uses it, for example). The nice part is that it, itself, is a nicely consumable class that is easy to understand and quick to use.
Here’s is a quick run down on how to use the class.
First, you instantiate the class in your script code:
var wRequest = new Sys.Net.WebRequest();
Then you set the URL which will be involved in the asynchronous web request.
wRequest.set_url(getPage);
Next, you set the very (GET or POST):
wRequest.set_httpVerb("GET");
Then you set the “user context”. This is a value of any kind that differentiates the response from one asynchronous request from another. The WebRequest class will attempt to complete the request asynchyronously and call a registered callback when it’s done – this contextual information will let you know to which request the callback is registered.
wRequest.set_userContext("user's context");
You then assign the compelted event handler:
wRequest.add_completed(OnWebRequestCompleted);
And fire off the request:
wRequest.invoke();
The first argument of your callback method “OnWebRequestCompleted” is a XmlHttpExecutor object that you can use to retrieve information about your request.
More information about WebRequest
More information about XmlHttpExecutor.