|
|||||||||||||||||||||||||
|
|||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis document describes a simple approach of implementing AJAX functionality in ASP.NET web applications. Pros and cons of using AJAX are also discussed. The document contains a working JavaScript and C#.NET code demonstrating the suggested solution. Why AJAXMost of you already know that AJAX stands for Asynchronous JavaScript and XML. This technology was introduced first by Microsoft (from my best knowledge) back in 1999, and had been known as “DHTML / JavaScript web application with remote calls”. The whole idea of the technology was to allow an internet browser to make an asynchronous HTTP call to remote pages/services, and update a current web page with the received results without refreshing the whole page. By creators’ opinion, this should have improved customers’ experience, making HTTP pages look and feel very similar to Windows applications. Because the core implementation of this technology was based on internet browser functionality, the usability was very limited at that time. But several years later, the technology has been reborn with new browsers support and massive implementation by such giants as Google, Amazon.com, eBay, etc. Today, it’s known as AJAX, and considered as a natural part of any dynamic web page with advanced user experience. Solution DescriptionThe suggested approach provides a very simple, yet effective implementation of the AJAX functionality. It’s very easy to maintain and change, does not require any special skills from developers, and, from our best knowledge, is cross-browser compatible. Basically, a regular AJAX-like implementation includes two main components: a client HTML page with JavaScript code making an AJAX call and receiving a response, and a remote page that can accept a request and respond with the required information. The JavaScript code on the client page is responsible for instantiating an Our approach is intended for use in ASP.NET applications, and considers the following possible scenarios:
All these considerations are illustrated by the diagram below:
ImplementationBasic AJAX JavaScript methodsI divided all the JavaScript methods into two parts: calling page specific JavaScript methods, and AJAX JavaScript methods common for all the calling pages. Specific methods include a callback method as well, as it is responsible for updating the page content. Common AJAX methods are responsible for instantiating an Getting an function GetXmlHttpObject(handler)
{
var objXmlHttp = null;
if (!window.XMLHttpRequest)
{
// Microsoft
objXmlHttp = GetMSXmlHttp();
if (objXmlHttp != null)
{
objXmlHttp.onreadystatechange = handler;
}
}
else
{
// Mozilla | Netscape | Safari
objXmlHttp = new XMLHttpRequest();
if (objXmlHttp != null)
{
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
}
return objXmlHttp;
}
function GetMSXmlHttp()
{
var xmlHttp = null;
var clsids = ["Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0",
"Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0",
"Msxml2.XMLHTTP.2.6","Microsoft.XMLHTTP.1.0",
"Microsoft.XMLHTTP.1","Microsoft.XMLHTTP"];
for(var i=0; i<clsids.length && xmlHttp == null; i++) {
xmlHttp = CreateXmlHttp(clsids[i]);
}
return xmlHttp;
}
function CreateXmlHttp(clsid) {
var xmlHttp = null;
try {
xmlHttp = new ActiveXObject(clsid);
lastclsid = clsid;
return xmlHttp;
}
catch(e) {}
}
According to Umut Alev, the code for the function GetMSXmlHttp() {
var xmlHttp = null;
var clsids = ["Msxml2.XMLHTTP.6.0",
"Msxml2.XMLHTTP.4.0",
"Msxml2.XMLHTTP.3.0"];
for(var i=0; i<clsids.length && xmlHttp == null; i++) {
xmlHttp = CreateXmlHttp(clsids[i]);
}
return xmlHttp;
}
As you see, function SendXmlHttpRequest(xmlhttp, url) {
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}
I use a GET HTTP method to a given URL, but this can be easily changed by changing the JS code above. Page-specific methodsNow we have all the methods we need to perform a call to the remote page. In order to do this, we need to pass the callback method name to the var xmlHttp;
function ExecuteCall(url)
{
try
{
xmlHttp = GetXmlHttpObject(CallbackMethod);
SendXmlHttpRequest(xmlHttp, url);
}
catch(e){}
}
//CallbackMethod will fire when the state
//has changed, i.e. data is received back
function CallbackMethod()
{
try
{
//readyState of 4 or 'complete' represents
//that data has been returned
if (xmlHttp.readyState == 4 ||
xmlHttp.readyState == 'complete')
{
var response = xmlHttp.responseText;
if (response.length > 0)
{
//update page
document.getElementById("elementId").innerHTML
= response;
}
}
}
catch(e){}
}
The The last question regarding the calling page implementation is how we call the Page.RegisterStartupScript("ajaxMethod",
String.Format("<script>ExecuteCall('{0}');</script>", url));
We can add this line of code either in the Remote PageLet’s find out what a remote page could look like. If this is an ASP.NET page (what we assume), we are interested in the code-behind only. We can easily remove all the code from the .aspx file: it won’t affect the behavior of the page in any way. For example, we take a public web service that converts temperature values in Celsius to Fahrenheit and vice versa. The service is available here. If you add this URL as a web reference to your project, Visual Studio will generate a proxy class with the name private void Page_Load(object sender, EventArgs e)
{
Response.Clear();
string temp = Request.QueryString["temp"];
if (temp != null)
{
try
{
int tempC = int.Parse(temp);
string tempF = getTempF(tempC);
Response.Write(tempF);
}
catch
{
}
}
Response.End();
}
private string getTempF(int tempC)
{
com.developerdays.ITempConverterservice
svc = new ITempConverterservice();
int tempF = svc.CtoF(tempC);
return tempF.ToString();
}
According to our convention, we can now build a URL string for the remote page that we will pass to the int tempC = 25;
string url = String.Format("http://localhost/" +
"getTemp.aspx?temp={0}", tempC);
Using the approach with an intermediate ASP.NET page, calling in its turn a remote service, allows simplifying response processing, especially if it requires parsing. In simple cases when the response contains just text, we can pass the remote service URL directly to the JS ConclusionThis article is aimed to illustrate the simplicity of using the AJAX technology in any ASP.NET application. While AJAX has some drawbacks, it also provides some advantages from the user experience perspective. It’s completely up to the developer whether to use the AJAX technology or not, but I have just demonstrated that in simple cases, it does not take a long time or require any special skills. CreditsI would like to thank my colleagues Oleg Gorchkov and Chris Page who helped me out with testing and optimizing the approach described in the article.
|
||||||||||||||||||||||||