Using AJAX with ASP
Using AJAX with ASP.NET - Working with DataSet (Part 2)
Introduction
In the
previous article I explained the overall concept of AJAX and how it can save
you server post backs. Our last example was a simple "hello world" kind of
example. In this part I will explain how to work with data from a DataSet to
populate controls.
Simple Example
In this example we will see how to populate controls with data from DataSet
using client side script. We will develop two web forms - DataSupplier.aspx and
DataConsumer.aspx. The former populates a DataSet consisting of Orders for a
specific Customer. The later consists of a DropDownList and a ListBox. The
DropDownList displays list of all the Customers from Customers table. When user
selects a specific CustomerID we call DataSupplier.aspx through AJAX and
populate the ListBox with the DataSet returned
- .Create a new Web Application in VS.NET
- Add two web forms to it - DataConsumer.aspx and DataSupplier.aspx
- Drag and drop a DropDownList and a ListBox on DataConsumer.aspx
- Write following code in the Page_Load event handler of DataConsumer.aspx
Private Sub Page_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim ds As New DataSet
Dim da As New SqlDataAdapter
("select customerid,companyname from customers",
"data source=.\vsdotnet;initial
catalog=northwind;user id=sa")
da.Fill(ds, "custoemrs")
DropDownList1.DataSource = ds
DropDownList1.DataValueField = "customerid"
DropDownList1.DataTextField = "companyname"
DropDownList1.DataBind()
End If
DropDownList1.Attributes.Add("onchange",
"return GetDataViaAJAX();")
End Sub
- Here, we populated a DataSet with all the customer records from
Customers table. We then bind this DataSet to the DropDownList
- We also attach a client side event handler for "onchange" event of the
DropDownList with GetDataViaAJAX() function.
- The GetDataViaAJAX() function is a client side JavaScript function that
calls DataSupplier.aspx via AJAX.
- In the .aspx file add following JavaScript function to the <HEAD>
section of the page
var obj;
function GetDataViaAJAX()
{
try
{
obj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
obj = null;
}
}
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open("GET", "http://localhost/AJAXDemo/datasupplier.aspx?
customerid=" +
document.getElementById("DropDownList1").value, true);
obj.send(null);
}
return false;
}
}
- This function is similar to what we wrote in the previous article.
- Note the part marked in bold. This time we call open() method by passing
the URL of datasupplier.aspx and pass the Customer ID selected in the
DropDOwnList as a query string parameter.
- Now let's write ProcessResponse() function that deals with the returned
data.
- Add following function after the above function
function ProcessResponse()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
var dsRoot=obj.responseXML.documentElement;
var ddlOrders = document.getElementById("ListBox1");
for (var count = ddlOrders.options.length-1;
count >-1; count--)
{
ddlOrders.options[count] = null;
}
var orders = dsRoot.getElementsByTagName('orderid');
var text;
var listItem;
for (var count = 0; count < orders.length; count++)
{
text = (orders[count].textContent ||
orders[count].innerText || orders[count].text);
listItem = new Option(text, text, false, false);
ddlOrders.options[ddlOrders.length] = listItem;
}
}
else
{
alert("Error retrieving data!" );
}
}
}
- Here, we created a function called ProcessResponse which will be called
when the datasupplier.aspx returns the response.
- This time we used responseXML property of the XMLHTTP instance because
our data is going to be in XML format.
- The documentElement property returns a reference to the root element of
the returned XML
- First we remove all the items from the ListBox by iterating through it
and setting individual item to null
- Then we retrieve all the OrderIDs by calling getElementsByTagName()
method of DOM. This method returns array of all the nodes with tag name of
orderid.
- We then iterate through all the elements of this array and add the Order
IDs to the ListBox.
- Now, add following code to the Page_Load event of datasupplier.aspx
Private Sub Page_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Dim ds As New DataSet
Dim da As New SqlDataAdapter("select orderid from orders
where customerid='" & Request.QueryString("customerid") & "'",
"data source=.\vsdotnet;initial catalog=northwind;user id=sa")
da.Fill(ds, "custoemrs")
Response.Clear()
Response.ContentType = "text/xml"
Response.Write(ds.GetXml())
Response.End()
End If
End Sub
- Here, we fill a DataSet with all the Orders for the CustomerID specified
in the query string
- We set content type of the response to "text/xml" as our data is XML.
- We retrieve the data in XML format by using GetXml() method of DataSet.
- Finally we send this XML data back to the client using Response.Write()
methiod.
- Set the DataConsumer.aspx as the startup page and run the application.
- Select any Customer from the DropDownList and you should get the
relevant Order IDs.in the ListBox.
Code Download
The complete source code of above sample is available for download along with
the article. Please see top of the article for download link.
Summary
In this article we saw how to work with data from a DataSet. The GetXml()
method of DataSet class comes handy for generating XML version of your data
instead of manually formatting it. In the next article I will show how the
values addeded from client side JavaScript can be accessed on the server.