Computer Services
professional website developers

ASP.NET

Home
About Us
Our Services
Contact Information
Articles

Ajax DataGrid

AjaxDataGrid.jpg

Introduction

This article describes how to update the data in ASP.NET 2.0 DataView control through AJAX.
Problem description: Let's consider that there is some ECommerce application that allows customers to buy some products on Internet. Each time the sale is done the remaining products quantity is updated. Let's also consider that it is necessary to monitor those quantities in real time (this can be required in case of high volume sales and the necessity to frequently order the required products). In such a case it will be useful to have a web page with the required products and units in stock data that will be updated through asynchronous calls on a required time interval (let's say 5 sec).
When I had a request to develop similar page I spent many hours on internet trying to find any working sample that can give me an idea on how to code this and I didn't succeed. Most of the articles had some beautiful words but didn't have any line of code, other articles had samples but they didn't work.
So after some amount of time I came with some approach on how to make this work and I hope this article will help other people who are trying to understand AJAX.

Background (optional)

The sample is using the data from Products table, Northwind database.
The approach is based on using XmlHttpRequest object using which you can send/get any data from/to server using JavaScript.
To implement AJAX call you actually need to have two web pages: the one that is visible to the end user and the second one that actually generated the required content for the first web page. The first page calls the second one through XmpHttpRequest implemented in JavaScript.

Using the code

In the the sample below we will have 2 web pages :
* the first one - Default.aspx - the page that will be shown to end user
* the second one - DataGrid.aspx - will provide the content to the Default.aspx page that will be updated each 5 seconds.

As it was told the sample is using Northwind database, the connection string to which is provided in web.config file:

<appSettings>
<add key="DSN" value="server=localhost;Integrated Security=SSPI;database=Northwind" />
</appSettings>

The Business Logic Layer is located in App_Code\BLL sobfolder and contains ProductsBLL.cs class that has one method GetProducts() that actually returns all products for CategoryId=1 from Products table, Northwind database.

/// Summary description for ProductsBLL
/// public class ProductsBLL
{
    public static void GetProducts(DataSet ds)
    {
        string sqlString = "SELECT ProductId, ProductName, QuantityPerUnit UnitPrice, UnitsInStock FROM Products WHERE CategoryId=1 order by ProductName";
        SqlHelper.FillDataset(SqlHelper.connection(), CommandType.Text, sqlString, ds, new string[] { "Products" });
    }
}       

The above method is using FillDataset method from Data Access Layer which is located in App_Code\DAL subfolder and contains one class SqlHelper.cs that contains a collection of data access methods. SqlHelper.cs class was created on a base of an open source Application Blocks data access classes and can be successfully used to access data in SQL database.

Let's consider now the DataGrid.aspx web page. This page contains Label1 control and gvGrid GridView control that are both populated on Page_Load event. DataView control is populated with the data from Products data set and Label1.Text is updated with the current date/time.

protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = new DataSet();
    ProductsBLL.GetProducts(ds);
    gvGrid.DataSource = ds;
    gvGrid.DataBind();

    Label1.Text = "Units in Stock for: " + DateTime.Now.ToString();
}

The Default.aspx page contains <div> section with the id="GridSection" and Input button btnGet that calls Ajax javascript function doCall() on onclickevent.
The data that will be received through AJAX calls will be placed inside the above <div> element.

<input id="btnGet" type="button" value="Get Data" onclick="doCall()"/>
.
.
.
<div id= "GridSection">

</div>

Now let's consider the Ajax.js javascript that actually does the whole job.

// Creating the instance of the XmlHttpRequest

// This is done differently for different browsers

// Branch for native XMLHttpRequest object

var client=null;
if (window.XMLHttpRequest)
{
    client = new XMLHttpRequest();
}

// Branch for IE/Windows ActiveX version

else if (window.ActiveXObject)
{
    client = new ActiveXObject("Microsoft.XMLHTTP");
}

//Sending information to server
function doCall()
{
    try
    {
        //callBack;
        var url="DataGrid.aspx"
        url=url+'?d='+Date();
        client.open("GET", url);
        client.onreadystatechange = callBack;
        client.send();
    }
    catch(ex)
    {
        alert(ex.message);
    }
 
    setTimeout('doCall()', 5000); //5 sec
}
 
//Waiting and processing server response
function callBack(response)
{
    try
    {
        if(client.readyState == 4 && client.status == 200)
        {
            xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
            xmlDocument.async = false;
 
            //The responseText is loaded into XML document
            xmlDocument.loadXML(client.responseText); 

         //Get the

        node vargridNode=xmlDocument.selectSingleNode('/html/body/form/div[@id="Grid"]');
 
            //Replace innerHTML of the default.aspx page with the response node.xml

            document.getElementById("GridSection").innerHTML=gridNode.xml;
        }
    }
    catch(ex)
    {
    alert(ex.message);
    }
}

To test the sample open Default.aspx page and click "Get Data" button.
The page will be populated with the DataView with products data from Products table, Northwind database. The data in the DataView are refreshed each 5 seconds.
To test this functionality open Northwind database, Products table and change UnitsInStock field's data for some product from CategoryId=1. The data on Default.aspx web page will be changed in 5 seconds without beign posted back.

Points of Interest

Using the above technique it is possible to update various parts of the page with different data asynchronously which can be useful when working with the data that should be refreshed to the user not only when the user posts back the page but rather at some certain time intervals.

A & G Web Development and Design
30-14 Garrison Ter., Fair Lawn NJ 07410
(201) 937-8711