Click here to Skip to main content
15,886,578 members
Articles / Web Development / ASP.NET

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

Rate me:
Please Sign up or sign in to vote.
3.44/5 (5 votes)
12 Apr 2009CPOL3 min read 59.6K   267   19   11
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.

JavaScript
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.

C#
/// <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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect Infosolvex Solutions Inc
Australia Australia
Ritesh is an IT consultant with over ten years of experience in the IT industry varying from consultation, architecture, design, development to technical management. He has a strong background in solutions and applications architecture with a focus on Microsoft’s .Net platform. His area of expertise spans design and implementation of client/server, database and web-based systems. He has worked with C#, ASP.NET 1.1 and 2.0, ADO.NET, Web Services and SQL technology on several enterprise class projects.




Freedom is not worth having if it does not include the freedom to make mistakes.
Mahatma Gandhi

Comments and Discussions

 
GeneralMy vote of 1 Pin
Syed J Hashmi9-Nov-09 4:51
Syed J Hashmi9-Nov-09 4:51 
GeneralReally premitive idea. Pin
Abhishek Sur13-Apr-09 21:39
professionalAbhishek Sur13-Apr-09 21:39 
GeneralRe: Really premitive idea. Pin
yafi14-Apr-09 6:05
yafi14-Apr-09 6:05 
GeneralRe: Really premitive idea. Pin
Ritesh Ramesh14-Apr-09 9:13
Ritesh Ramesh14-Apr-09 9:13 
GeneralRe: Really premitive idea. Pin
Abhishek Sur15-Apr-09 21:42
professionalAbhishek Sur15-Apr-09 21:42 
GeneralRe: Really premitive idea. Pin
Ritesh Ramesh16-Apr-09 5:41
Ritesh Ramesh16-Apr-09 5:41 
Hey good to see your reply,

I just don't get why you would avoid using a different extension for a HTTPhandler because you need to register it on IIS. It takes 5 min to register a handler if you have done it before. Its like saying I don't like the bother that comes with complications of creating/registering for a new email account I will just use my friends since he already has one. I have rolled out more projects using custom extensions than I can remember. But surely not creating a new extension for the sake of a minor deployment routine(a 3 step GUI based administrative task) is an excuse way beyond what I can comprehend. Unless of course you are dealing with shared hosting environments all your life and u need to get on the phone to talk to someone who doesn't exist Smile | :) even then I suggest you change your hosting!


Of course it has to do with code manageability, haven't you heard of encapsulation? Reusing an existing extension will require you to modify your existing code, which means if you haven't designed your handler to implement multiple types of requests you are going to be stuck with a design issue, new design means more testing, add to this the performance hit by your existing handler to differentiate between whatever request it was designed for and the new request it has to manage, when IIS is managing all this for you by creating a new handler at a lower level anyway!


Further think about the security, I can filter based on Get/Post for this particular handler, I can even authenticate based on who or what is passing me a request, where as an existing handler may require a different set of filters. I can go on about why you should use a different extension but this conveys enough I guess.
GeneralRe: Really premitive idea. Pin
Abhishek Sur20-Apr-09 22:16
professionalAbhishek Sur20-Apr-09 22:16 
GeneralRe: Really premitive idea. Pin
Ritesh Ramesh21-Apr-09 3:55
Ritesh Ramesh21-Apr-09 3:55 
GeneralRe: Really premitive idea. Pin
Abhishek Sur21-Apr-09 22:38
professionalAbhishek Sur21-Apr-09 22:38 
GeneralRe: Really premitive idea. [modified] Pin
Ritesh Ramesh22-Apr-09 2:45
Ritesh Ramesh22-Apr-09 2:45 
GeneralRe: Really premitive idea. Pin
Abhishek Sur22-Apr-09 21:36
professionalAbhishek Sur22-Apr-09 21:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.