X

AJAX Drop Down List – Part One

I wrote a tutorial on using AJAX technology in ASP.NET applications, and it only shows a very simple but common use of AJAX. Another common use of AJAX is to populate a drop down list based on the selection of another drop down list without using post back. It is especially useful when populating a large drop down list and the connection is not so fast.

Let’s get started.

Before we go too far, let’s review some background information of AJAX technology. There are usually three parts in one AJAX job.

  1. A client page to display the drop down lists;
  2. A server page to retrieve data asynchronously;
  3. The client page has some JavaScript code to handle the data.

1. Client Side Page ProductList.aspx

The client side page is very straight-forward, and it contains two drop down lists, say one is called “ddlParentList”, and the other one is called “ddlChildList”. The child drop down list will be populated based on the selection of the parent drop down list.

The sever page is where you get the data from your database and then store the data in the output stream by using Response.Write(stringToWrite). There are two types of data you can write into Response stream: plain string data and XML data. In this tutorial I will explain how to pass plain string data to the client side, and in the next tutorial I will explain how to pass XML data to the client side.

2. Server Side Page GetList.aspx

GetList.aspx does not have any UI because the only purpose of the server side page is to get data from database based on the query string passed from JavaScript code which embedded in the client side page ProductList.aspx.

The code behind of GetList.aspx will be like this (VB.NET):

Private Sub Page_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles MyBase.Load

‘Put user code to initialize the page here

If Not IsPostBack() Then

Dim company As String
company= Request.QueryString(“objectValue”)
Dim ds As New dsProductList
Dim appHandler As New ApplicationHandler
ds = appHandler.GetProductList(company)
Dim sb As New System.Text.StringBuilder
Dim dr As New dsProductList.ProductRow
Dim index As Integer

‘Generate a string like |ProductName1, ProductID1|ProductName2, ProductID2|…
‘Then at the client side, the JavaScript code will split the string to populate the child drop down list.
sb.Append(“|”)

For index = 0 To ds.Product.Rows.Count – 1

dr = CType(ds.Product.Rows(index), dsProductList.ProductRow)
sb.AppendFormat(“{0}, {1}{2}”, dr.CompanyName, dr.CompanyID, “|”)

Next

sb.Remove(0, 1)
Dim retVal As String
retVal = sb.ToString()
Response.ClearContent()
Response.Write(retVal)
Response.End()

End If

End Sub

Here dsProductList is a Strong Typed DataSet, and ApplicationHandler is a Data Access Layer class, and you don’t have to do the same as mine. The point here is to get data from database and then generate a delimited string passing to the client side. The AJAX code (or JavaScript code) will parse the string after receiving the string, then populate the child drop down list.

3. Client Side JavaScript Code

1). Preparation – prepareRequest()
In this stage, JavaScript code will get the selected value of the parent drop down list and the URL to the server side GetList.aspx, then pass them to the second stage: Initialization.

Here is the code:

function prepareRequest()
{
var pList = document.getElementById("ddlParentList");
var company = pList.value;
url = '../AJAX/GetList.aspx?objectValue=' + company;
makeRequest(url); <== go to the second stage
}

2). Initialization – makeRequest(url)
In this stage, we first need to instantiate a XMLHttpRequest instance, then use this instance to open the connection between the client side and the server side. Once the connection is in place, the process will go to the third stage: Processing Data.

Here is the code:

function makeRequest(url)
{
var http_request = false;
if (window.XMLHttpRequest)
{
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
 }
catch(e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{ }
}
}
if(!http_request)
{
alert('Giving up: (Cannot create an XMLHTTP instance');
return false;
 }
http_request.onreadystatechange = function() { populateDropDownList(http_request); };
http_request.open('GET', url, true);
http_request.send(null);
 }

The try-catch blocks in the code are to handle different web browsers, such as IE, FireFox, Netscape, and etc. The very last three lines of code set up the connection and process data from the server side page.

3). Processing Data – populateDropDownList(http_request)
In this stage, the data passed in from the server side page is processed.

Here is the code:

function populateDropDownList(http_request)
{
var lbl = document.getElementById('lblResults');
if(http_request.readyState == 0)
{
lbl.innerHTML = "Initializing...";
}
else if (http_request.readyState == 1)
{
lbl.innerHTML = "Process request...";
}
else if (http_request.readyState == 2)
{
lbl.innerHTML = "Request acknowledged.";
}
else if(http_request.readyState == 3)
{
lbl.innerHTML = "Loading data...";
}
else if (http_request.readyState == 4 && http_request.status == 200)
{
var cList = document.getElementById("ddlChildList");
var pairedList = http_request.responseText.split("|");
if(pairedList.length == 0)
{
lbl.innerHTML = "No product is available for this company.";
}
else
{
var itemText;
var itemValue;
lbl.innerHTML = "";
var itemPair;
var optionItem;
for (var index = 0; index < pairedList.length; index++)
{
itemPair = pairedText[index].split(",");
itemText = itemPair[0];
itemValue = itemPair[1];
optionItem = new Option(itemText, itemValue, false, false);
cList.options[cList.length] = optionItem;
}
}
}
}

4. Putting Together
The three JavaScript functions need to be placed in the <HEAD> section of the client side page ProductList.aspx, and an “onchange” attribute needs to be added to the parent drop down list.

<asp:dropdownlist id=”ddlParenList” runat=”server” onchange=”prepareRequest”></asp:dropdownlist>

In the part two of AJAX Drop Down List tutorial, I will describe how to use XML to populate the child drop down list.

Jeffrey:
Related Post