Oct
12
2006
Your first ASP.NET script with Ajax
Posted by admin under
Ajax

This is just a very basic example on how to deliver Ajax functionality from your ASP.NET applications.
The downloadable solution contains two code files - but lets start with looking at the screenshots:

The idea is we should be able to just click the "Refresh time below" link and get a new date - without the page reloading:

So easy enough. Lets look at the code - first we start off with the the simple stuff. The first datetime is just a asp:label which gets it value set in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString();
}
Now for the cool stuff. The basic idea in this simple solution is to have the second datetime as a HTML div - and when clicking on the "Refresh time below" link we make our serverside call, receives a new datetime string - and sets the div.innerHtml to the string.
Lets start by defining the controls:
<form id="form1" runat="server">
<div>
Time is now (when page loads): <asp:Label ID="lblTime" runat="server"></asp:Label>
<br />
bla bla
<br /><br />
<a href="javascript:AjaxGetData('ajax.ashx?what=time', timeHandler);">Refresh time below:</a>
Time after AJAX call:
<div id="NewTime"></div>
<br />
</div>
</form>
As you can see from above - thats the whole body part of our aspx page. We have a div with id set to NewTime - and the hyperlink (a tag) calls a JavaScript function - AjaxGetData - sending in the url to a ajax.ashx?what=time - and something called timeHandler.
As you might guess somehow we will call the ajax.ashx page which is a ASHX handler looking like this:
<%@ WebHandler Language="C#" Class="ajax" %>
using System;
using System.Web;
public class ajax : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "text/plain";
if ( context.Request["what"] == "time" )
context.Response.Write( DateTime.Now.ToString() );
}
public bool IsReusable {
get {
return false;
}
}
}
Now lets go back to AjaxGetData('ajax.ashx?what=time', timeHandler):
The timeHandler is another javascript function - the idea is to spawn off the request for ajax.ashx?what=time (which will give us a string containing the current time) - and specifying a callback function - it will automatically be called when the request is finished.
So - that function callback looks like this:
function timeHandler()
{
try
{
//readyState of 4 or 'complete' represents
//that data has been returned
if (req.readyState == 4 ||
req.readyState == 'complete')
{
document.getElementById('NewTime').innerHTML = req.responseText;
}
}
catch(e)
{
alert('Error in Ajax respone');
}
}
We are somehow able to retrieve the returned string through req.responseText (I will get into the req object soon) - and we simply just set the innerHTML to it.
Now - lets look at the AjaxGetData javascript:
function AjaxGetData(url, responseHandler)
{
if (window.XMLHttpRequest)
{
// browser has native support for XMLHttpRequest object
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// try XMLHTTP ActiveX (Internet Explorer) version
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(req)
{
req.onreadystatechange = responseHandler;
req.open('GET', url, true);
req.setRequestHeader("content-type","application/x-www-form-urlencoded");
req.send('');
}
else
{
alert('Your browser does not seem to support XMLHttpRequest.');
}
}
This is the function doing the actual call. First we need to do some checks on how to make call - depending on which browser the user is using - and with the req.onreadystatechange we are able to hook into the event handler system around the call - this will mean our timeHandler function will be called.
So just download the solution and try it out for yourself - VS2005 and C# has been used.
Attachments