Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / XHTML

Using AJAX with ASP.NET 2.0

3.64/5 (8 votes)
13 Jul 2008CPOL4 min read 1   948  
This article demonstrates how to use AJAX with ASP.NET 2.0.

Introduction

AJAX is an acronym for Asynchronous JavaScript and XML. It is the latest buzzword amongst web programmers. It is not exactly a new technology, but a combination of several technologies like JavaScript and XML, which allows remote scripting. AJAX creates an asynchronous request to the web server using client-side JavaScript and an XmlHttpRequest object, and map a function to be executed when the response is received. An asynchronous request means that the browser does not need to wait for the response after sending the request to the server. This creates a responsive user interface without the form being posted back to the server for fetching small amounts of data.

In this article, I will be demonstrating an application of Google Suggest type, in which as a user types text in a textbox, a list of suggestions would be displayed.

This article assumes that the reader has an understanding of ASP.NET, C#, ADO.NET, JavaScript, XML, and XSLT.

The following is an outline of the sequence of events when an ASP.NET AJAX page is rendered:

  1. Web page is rendered.
  2. A JavaScript function is executed by a trigger (i.e., onKeyUp, button click etc.).
  3. JavaScript instantiates an XMLHTTPRequest object.
  4. The XMLHTTPRequest object calls a remote page.
  5. The remote page transforms an XML structure using XSLT and returns the result.
  6. JavaScript accepts the results and applies it to the page.
  7. The web page is rendered without a postback to the server by getting the requested data from the remote page.

Creating the XMLHTTPRequest Object

The method of creating the XMLHTTPRequest object varies from browser to browser. IE implements this object using ActiveX technology, while Firefox, Opera, and Safari implement this as a native object.

The code presented here first tires to create the object if the browser is Firefox, Safari, or Opera (objXmlHttp=new XMLHttpRequest();). If the browser is not one of these, then it tries to create the object for IE 6 and above (objXmlHttp=new ActiveXObject("Msxml2.XMLHTTP");). If the browser is IE6 or earlier, then the object is created as objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP");. If the object couldn’t be created, then an alert is displayed saying that the browser doesn’t support AJAX.

JavaScript
function GetXmlHttpObject(handler) 
{
    var objXmlHttp;
    
    try
    { 
        // Firefox, Opera 8.0+, Safari  
        objXmlHttp=new XMLHttpRequest();  
        objXmlHttp.onload = handler; 
        objXmlHttp.onerror = handler; 
    }
    catch (e)
    {  
        // Internet Explorer6+  try
        try
        {
            objXmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
            objXmlHttp.onreadystatechange = handler;    
        }
        catch (e)
        {    
            try
            {      
                objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
                objXmlHttp.onreadystatechange = handler;         
            }
            catch (e)
            {      
                alert("Your browser does not support AJAX!");      
                return false;      
            }
        }
        return objXmlHttp;
    }

Properties of the XMLHTTPRequest Object

  • onreadystatechange - A property of the XMLHTTPRequest object has been used which is onreadystatechange. This is the response handler function, which gets called for every change of the readyState property.
  • readyState - The state of the receiving request.
  • status - The HTTP status code returned by the server.
  • responseXML - The XML document returned by the server.

Methods of the XMLHTTPRequest Object

  • open - Initializes a request.
  • send - Sends a request to the server.

statechangehandler function

The stateChangeHandler will fire when the state has changed, i.e., data is received back. This is non-blocking (asynchronous).

JavaScript
function stateChangeHandler() 
{ 
    //readyState of 4 or 'complete' represents that data has been returned 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
    { 
        //Gather the results from the callback 
        var str = xmlHttp.responseText; 

        //Populate the innerHTML of the div with the results 
        document.getElementById('nameList').innerHTML = str;
    } 
    
    if (xmlHttp.readyState == 1)
    { 
        //Populate the innerHTML of the div with the results 
        document.getElementById('nameList').innerHTML = 'LOADING...';
    }
}

xmlHttp_Get function

Creates the request and sends it to the server.

JavaScript
function xmlHttp_Get(xmlhttp, url) 
{ 
    xmlhttp.open('GET', url, true); 
    xmlhttp.send(null); 
}

The complete JavaScript code is as follows:-

JavaScript
var xmlHttp; 
var requestURL = 'Names.aspx?q='; 

function show_data(strName)
{ 
    if (strName.length > 0)
    { 
        //Append the name to search for to the requestURL 
        var url = requestURL + strName; 
         
        //Create the xmlHttp object to use in the request 
        //stateChangeHandler will fire when the state 
        //has changed, i.e. data is received back 
        // This is non-blocking (asynchronous) 
        xmlHttp = GetXmlHttpObject(stateChangeHandler); 
         
        //Send the xmlHttp get to the specified url 
        xmlHttp_Get(xmlHttp, url); 
    } 
    else 
    { 
        //Textbox blanked out, clear the results 
        document.getElementById('nameList').innerHTML = '';
    } 
}

//stateChangeHandler will fire when the state
//has changed, i.e. data is received back 
//This is non-blocking (asynchronous) 
function stateChangeHandler() 
{ 
    //readyState of 4 or 'complete' represents that data has been returned 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
    { 
        //Gather the results from the callback 
        var str = xmlHttp.responseText; 

        //Populate the innerHTML of the div with the results 
        document.getElementById('nameList').innerHTML = str;
    } 
    
    if (xmlHttp.readyState == 1)
    { 
        //Populate the innerHTML of the div with the results 
        document.getElementById('nameList').innerHTML = 'LOADING...';
    }
}

// XMLHttp send GET request 
function xmlHttp_Get(xmlhttp, url) 
{ 
    xmlhttp.open('GET', url, true); 
    xmlhttp.send(null); 
}

function GetXmlHttpObject(handler) 
{
    var objXmlHttp;
    
    try
    { 
        // Firefox, Opera 8.0+, Safari  
        objXmlHttp=new XMLHttpRequest();  
        objXmlHttp.onload = handler; 
        objXmlHttp.onerror = handler; 
    }
    catch (e)
    {  
        // Internet Explorer  try
        try
        {
            objXmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
            objXmlHttp.onreadystatechange = handler;    
        }
        catch (e)
        {    
            try
            {      
                objXmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
                objXmlHttp.onreadystatechange = handler;         
            }
            catch (e)
            {      
                alert("Your browser does not support AJAX!");      
                return false;      
            }
        }
        return objXmlHttp;
    }
}

The onKeyUp attribute of the HTML textbox triggers the function named show_data(string) which invokes the function to send the request to the remote page.

Client and Remote Pages

The client named Default.aspx (can be Default.htm) contains the JavaScript which sends the request to the remote page Names.aspx.

The complete JavaScript is placed in an external script file named AjaxGetNames.js.

The JavaScript request contacts the remote page. The variable “q” is passed in the query sting to contain the data that the user types in the textbox. An XML string is constructed based on the term. An XSL transform is applied on the XML data.

The ADO.NET code of the remote page queries the Customers table of the Northwind database and finds the names matching the text being typed in the textbox, displaying the suggested names in the div tag.

C#
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;

public partial class Names : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["q"] != null)
        {
            GetNames();
        }
    }
    
    private void GetNames()
    {
        string strQuery = Request.QueryString["q"];

        //Create the XML-like string to be sent back to the request 
        string strXmlNames = "";

        ArrayList al = new ArrayList();
        al = RetreiveNames();

        // Copies the elements of the ArrayList to a string array.
        String[] arrStrNames = (String[])al.ToArray(typeof(string));

        foreach (string strName in arrStrNames)
        {
            strXmlNames += "<user><name>" + strName + "</name></user>";
        }
        strXmlNames = "<users>" + strXmlNames + "</users>";

        //Create an XmlDocument object to store 
        //the XML string that we created 
        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(strXmlNames);

        //Create a navigator object to use in the XSL transformation 
        XPathNavigator xPathNav = xDoc.CreateNavigator();

        //Create the XSLTransform object 
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(Server.MapPath("Names.xslt"));

        //Do the transformation and send the results 
        //out to the Response object's output stream 
        xslt.Transform(xPathNav, null, Response.OutputStream);
        
    }

    public ArrayList RetreiveNames()
    {
        ArrayList al = new ArrayList();

        SqlConnection con = new SqlConnection();
        con.ConnectionString = 
            "Data Source=.;Integrated Security=True;Database=Northwind";

        SqlCommand cmd = new SqlCommand("SELECT ContactName from Customers" + 
                         " WHERE ContactName LIKE UPPER('" + 
                         Request.QueryString["q"] + "%')", con);
        
        con.Open();

        SqlDataReader rdr = cmd.ExecuteReader();

        while (rdr.Read())
        {
            al.Add(rdr[0].ToString());
        }
        return al;
    }
}

Conclusion

In this article, I have demonstrated that AJAX is a technology that employs JavaScript to initiate an asynchronous request to the server and to handle an XML response from the server. A sample ASP.NET application has been demonstrated that uses AJAX to dynamically get a list of names matching those from the database as user types text in the textbox, without requiring the form to post back to the server. In this way, I have illustrated that AJAX allows an ASP.NET web page to provide for a more responsive user interface.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)