9.2. Making WebRequest Calls

The WebRequest class is the central object used for managing HTTP requests in ASP.NET AJAX. It provides a cross-browser compatible object for using the different underlying XMLHttpRequest implementations. Listing 9-3 (CallTimeWebRequest.aspx) is a Web page that does the equivalent of the request and response processing shown in Listing 9-2.

Example 9-3. CallTimeWebRequest.aspx
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Networking</title>
<script type="text/javascript">

var xmlhttp;

function pageLoad() {
var  Request = new Sys.Net.WebRequest();
    webRequest.set_url("Time.aspx");

    webRequest.add_completed(completedHandler);
    webRequest.invoke();
}

function completedHandler(result, eventArgs) {
    if(result.get_responseAvailable()) {
        alert(result.get_statusText());
        alert(result.get_responseData());
    }
}
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager runat="server" ID="ScriptManager1">
    </asp:ScriptManager>
    <div>
    </div>
    </form>
</body>
</html>

First, note that the code creates a Sys.Net.WebRequest object directly. You do not have to bother with checking the browser compatibility. You set the service address, add a completed callback function, and invoke the request. In the callback function, there is no need to check different integers against the status codes they represent. Instead, ...

Get Professional ASP.NET 3.5 AJAX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.