Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to write your own partial postback in ASP.NET 2.0

0.00/5 (No votes)
12 Apr 2009 1  
Writing your own partial postback in ASP.NET 2.0.

Introduction

AJAX has been around for a while now, and an important feature of the AJAX implementation in the .NET space is the partial post back functionality of web pages. This functionality has made the online experience richer and smoother while decreasing bandwidth usage between the server and browser. How this technology works is equally fascinating, and I am making an attempt to demonstrate how it works by taking a look below the hood.

Background

At the heart of the partial post back construction is the XMLHttpRequest, a DOM API. It can be used inside a web browser scripting language, such as JavaScript, to send an HTTP request directly to a web server without having to reload the entire page and handling the response from the server again within the scripting language. This data, in the form of XML, can then be used to manipulate the page elements on the client side.

On the server side, we implement an HttpHandler to handle the request and pass back data in a valid XML form.

By doing so, we are preventing page refreshes and roundtrips of static data and content in the web pages.

Essential building blocks

  1. XMLHttpRequest API
  2. HTTPHandler

How the code works

When the button on the ASPX page has been clicked, a client side HTTP request is made using the XMLHttpRequest API. This request is handled by an HttpHandler on the web server. The HttpHandler receives the request, processes it, and sends back the response to the XMLHttp object on the ASPX page. The XMLHttp object in turn consumes the response and renders the appropriate UI changes without the browser having to do a full refresh of the page.

Using the code

XMLHttpRequest API

This API makes the client side request to the handler without the need for a full postback by the ASPX page. The XML data is received by the XMLHttp object and used to populate a div element.

var xmlhttp;
function loadXMLDoc()
{
    xmlhttp=null;
    if (window.XMLHttpRequest)
    {
      // code for all new browsers
      xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
      // code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp!=null)
    {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET", 
        "http://localhost:45000/.tpl",true);
      xmlhttp.send(null);
    }
    else
    {
      alert("Your browser does not support XMLHTTP.");
    }
}

function state_Change()
{
  if (xmlhttp.readyState==4)
  {
    if (xmlhttp.status==200)
    {
       document.getElementById('D').innerHTML=xmlhttp.responseText;
    }
    else
    {
      alert("Problem retrieving XML data:" + xmlhttp.statusText);
    }
  }
}

Httphandler

The HttpHandler code builds and sends a simple XML object called note, with a single element called body. You can modify and implement your own logic here to do more complex stuff.

/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("<note>");
        context.Response.Write("<body>Partial postbacks" + 
                               " are awesome!</body>");
        context.Response.Write("</note>");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Points of interest

Interestingly enough, much of the functionality we see above has been due to the browser support for XMLHttpRequest. It is important to understand the various implementations of the XMLHttp object by different browsers. Below is some history on the evolution of the XMLHttp object.

"Microsoft developers were the first to include the XMLHttp object in their MSXML ActiveX control. Developers at the open source Mozilla project saw this invention, and ported their own XMLHttp, not as an ActiveX control, but as a native browser object called XMLHttpRequest. Konqueror, Opera, and Safari have since implemented similar functionality, but more along the lines of an identical XMLHttpRequest. Some AJAX developers and run-time frameworks only support one implementation of XMLHttp while others support both. Developers building AJAX functionality from scratch can provide if/else logic within their client-side JavaScript to use the appropriate XMLHttp object as well. Internet Explorer 7 added native support for the XMLHttpRequest object, but retains backward compatibility with the ActiveX implementation. To avoid excess conditionals, see the source code in the History and support section." courtesy Wikipedia.

References

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here