![]() |
Web Development »
Ajax and Atlas »
Samples
Intermediate
License: The Code Project Open License (CPOL)
Using AJAX with ASP.NET 2.0By sudipta.indiaThis article demonstrates how to use AJAX with ASP.NET 2.0. |
C# (C#2.0), Javascript, XML, XHTML, XSLT, .NET (.NET2.0), ASP.NET, Ajax
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
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:
onKeyUp, button click etc.). XMLHTTPRequest object. XMLHTTPRequest object calls a remote page. 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.
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;
}
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. open - Initializes a request. send - Sends a request to the server. The 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...';
}
}
Creates the request and sends it to the server.
function xmlHttp_Get(xmlhttp, url)
{
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
The complete JavaScript code is as follows:-
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.
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.
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;
}
}
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.
| You must Sign In to use this message board. | |||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
|
|||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 13 Jul 2008 Editor: Smitha Vijayan |
Copyright 2008 by sudipta.india Everything else Copyright © CodeProject, 1999-2010 Web22 | Advertise on the Code Project |