WebRequests to the Page
ASP.NET AJAX provides some powerful networking tools to create dynamic applications on the fly. Most people are aware of the ways that web services are used in ASP.NET AJAX, using the Sys.Net.WebServiceProxy (or a proxy that uses this class under the hood) to call the service's methods.
Another object involved in all of this is the WebRequest object. Take a look at the code below.
function invokeRequest(url) {
var request = new Sys.Net.WebRequest();
request.set_url(url);
request.set_httpVerb("POST");
request.set_body("Some=True;Control=True");
request.get_headers()["Content-Length"] = request.get_body().length;
request.get_headers()["AJAXPostback"] = "True";
request.add_completed(requestCompleted);
request.invoke();
}
function getPageUrl() {
return "WebRequestAspxTest.aspx";
}
The WebRequest object has a few parameters: url, httpVerb, body, headers, and a few others not specified (timeout, etc.) that can perform a callback to the page. This callback is not a web service callback and doesn't require the WebMethod attribute defined on a page method. Instead, it will invoke a callback to the page, and run the page lifecycle. By making the call above (which references the same page as where the script lives), it will invoke the following code:
if (Request.Headers["AJAXPostback"] != null)
{
this.lblResults.Text += "Operation posted to the server<br/>";
Response.Write("Output Text");
}
You may expect that it outputs the text and returns the results; actually, the execution success callback fires:
function requestCompleted(executor, args) {
var label = $get("<%= lblOperationResults.ClientID %>");
if (executor.get_responseAvailable())
label.innerHTML += "Operation Completed<br/>";
else {
if (executor.get_timedOut())
label.innerHTML += "Operation Timed Out<br />";
else
if (executor.get_aborted())
label.innerHTML += "Operation aborted<br />";
}
}
This code executes, but what is the actual result? Actually, the results of the entire page rendering are available in the executor.get_responseData() property; this property contains the HTML contents as a string, because it's actually invoking a page request. While this may not be the most helpful, we're going to look at ways to make it easier to use, using a HTTP handler.