All posts related to ASP.NET AJAX

How to install ajaxcontroltoolkit in visualstudio 2010

AJAX::Edit Update Delete Using Accordion Control Using EDM

AJAX SlideShow Control

AJAX Autocomplete Extender using EDM

AJAX Autocomplete Extender using XML

AJAX Accordion Control with EDM

AJAX Accordion Control using XML DataBase

AJAX Rating Control using EDM with LINQ

Ajax CollapsiblePanelExtender

Gridview Edit&Update Using AJAXModalPopupControl

Gridview Edit,Update&Delete Using AJAXHoverMenuExtender

Ajax :: Calender Extender For TextBox in


Introduction to Ajax on ASP.NET

Traditionally, web applications have left a lot to be desired from a user experience standpoint, due primarily to the “request/response” lifecycle. Any interaction with a page typically requires a postback to the web server (a “request”), which then performs any server-side tasks needed and returns the updated page’s markup (the “response”). Outside of intranet-based applications, such behavior adds a bit of a lag when interacting with a page. One approach to improving the end user’s experience is to use AJAX. AJAX is a technique for using JavaScript and the XMLHttpRequest object to make light-weight HTTP requests back to the web server from client-side script. Once a response is received, the web page’s layout can be seamlessly refreshed using JavaScript to message the page’s Document Object Model (DOM) and CSS settings. AJAX-enabled pages provide a slick, responsive user experience, making web-based applications function more like desktop-based ones.

AJAX stands for Asynchronous JavaScript and XML. Using its techniques you can make your web applications more responsive and interactive. At the very core of AJAX lies the XMLHttpRequest object. This object facilitates in the sending of smaller amounts of data to the web server asynchronously, instead of having to refresh the entire page every time the user makes a change to it. As mentioned before, in the past, AJAX techniques were difficult to implement because developer’s were responsible for writing the client-side JavaScript to make the asynchronous request and handle its response, as well as the server-side code to handle such “partial” postbacks. Furthermore, subtle differences in the DOM and XMLHttpObject implementation across browsers didn’t help to make things any easier.

The Atlas framework is Microsoft’s answer to the difficulties inherent in implementing AJAX techniques. Atlas is an extension of ASP.NET and, as such, is incredibly easy to implement in your ASP.NET web applications. For example, with Atlas you no longer have to worry about cross-browser compatibility, because the framework outputs the correct code depending on the client’s user agent (web browser).

A Basic Atlas Example

Instead of just talking about Atlas, let’s get our feet wet and demonstrate the basic ideas using a simple example. You will first need to go to Atlas website ( and download and install the April CTP setup (.msi) file. During the installation just keep all the default settings. This setup file will install an Atlas website template into your Visual Studio 2005 or Visual Web Developer installation.

Now that you have the Atlas template installed, we can step through our first example. Fire up Visual Studio 2005. Once open, click on New Web Site from the File menu. You will see a dialog box similar to the one shown below.

Select the Atlas Web Site item under My Templates, type in a location, and click OK. The Atlas Web Site template has now done some initial setup for you. For example, from the solution explorer, if you look under the /bin directory, you will see the Microsoft.Web.Atlas.dll assembly has already been included in the project for you. Moreover, if you view the source of your Web.config file, you will see all the hooks needed to start adding Atlas functionality to you web application. (I will not be going into the details pertaining to the code Atlas puts in the Web.config. If you want to learn about what all this markup means, check out the Atlas documentation (

Lastly, if you view the source of the Default.aspx page you will see Atlas has added a new server control declaration:

<atlas:ScriptManager ID=”ScriptManager1″ runat=”server” />

In every page that you want to enable Atlas functionality, you must have exactly one ScriptManager control declared. We will ignore for now the <script> block at the bottom of this page and dive directly into our example.

To start, insert the following code snippet into your Default.aspx page, replacing the existing code between the <form> tags:

<form id=”form1″ runat=”server”>
    <atlas:ScriptManager ID=”ScriptManager1″ runat=”server” EnablePartialRendering=”true”/>
    <div style=”background-color: Yellow; float: left; width: 100px;”>
      <asp:Label ID=”FullPostBackLabel” runat=”server” /><br />
      <asp:Button ID=”FullPostBackButton” runat=”server” text=”Full Post Back” OnClick=”FullPostBackButton_OnClick” />
    <atlas:UpdatePanel runat=”server” ID=”UpdatePanel1″ Mode=”Conditional”>
        <div style=”background-color: Lime; width: 100px;”>
          <asp:Label ID=”PartialPostBackLabel” runat=”server” /><br />
          <asp:Button ID=”PartialPostBackButton” runat=”server” text=”Partial Post Back” OnClick=”PartialPostBackButton_OnClick” />

In short, this declarative markup creates two user interfaces, both of which update a Label control based on the current date and time on the server. The first interface uses the standard, request/response postback (the “Full Post Back” controls), while the second one will use AJAX to make partial postbacks. I’ll bypass discussing the “Full Post Back” controls, as those should be self-explanatory; instead, let’s focus on the “Partial Post Back” controls.

As you can see, the EnablePatialRendering attribute of the ScriptManager control has been added and its value set to True. This will allow ASP.NET to post only parts of the page back to the server instead of having to refresh the entire page. This is what we want! To handle posting data back to the web server asynchronously, you need to add an UpdatePanel control to your page:

<atlas:UpdatePanel runat=”server” ID=”UpdatePanel1″ Mode=”Conditional”>

Place those ASP.NET controls that participate in the asynchronous postback within the UpdatePanel’s <ContentTemplate> tags. The UpdatePanel’s Mode attribute dictates when the partial postback ensues. For this page, set the Mode attribute to Conditional, which means that the UpdatePanel will post its data back to the server if one of the following three events occur:

  1. The UpdatePanel’s Update() method is called explicitly
  2. An UpdatePanel event causes the Update() method to be called implicitly
  3. A server control that is inside the UpdatePanel causes a postback

If you leave out the Mode attribute, it will default to Always, which will cause the UpdatePanel to refresh when any server control on the page causes a post back. In this example we will be using the third option for posting back the UpdatePanel (that is, the UpdatePanel will postback when a control within it causes a postback). As you can see, we have a Label and Button control inside of the <ContentTemplate> tag. Therefore, the UpdatePanel will postback when the Button control is clicked.

Lastly, add the following server-side <script> block between the page’s <head> tags (you could also add this to the page’s code-behind class, if you’d rather):

<script runat=”server”>
  void FullPostBackButton_OnClick(object sender, EventArgs e)
    FullPostBackLabel.Text = DateTime.Now.ToString();
  }   void PartialPostBackButton_OnClick(object sender, EventArgs e)
    PartialPostBackLabel.Text = DateTime.Now.ToString();

These are the server-side event handlers for the two Button controls on the page (one inside the UpdatePanel and the other outside), which will update the Labels above them with the server’s current date and time.

Run the project now and click each button once. After doing so your screen should look similar to the following: 

When you clicked the button labeled “Partial Post Back”, you saw how the date and time above it were updated without any flicker in the screen, without a full-page post back, and without changing the other section’s time and date! Clicking the “Partial Post Back” button invoked an asynchronous postback to the web server using the XMLHttpRequest object; the web server then sent back information, which was used to update the screen dynamically. This simple example demonstrates just how easy it is to implement AJAX behaviors in your web application using Atlas.

At this point your imagination may be running wild, thinking of all the different possibilities of using ASP.NET 2.0 Web controls in AJAX scenarios. In our next example we will take the GridView control and show how easy it is to add partial post backs to update, sort, and page records!

Advantages of Ajax

The advantages of Ajax over classical web based applications are:

  • Asynchronous—Ajax allows for the ability to make asynchronous calls to a web server. This allows the client browser to avoid waiting for all data to arrive before allowing the user to act once more.
  • Minimal data transfer—By not performing a full postback and sending all form data to the server, the network utilization is minimized and quicker operations occur. In sites and locations with restricted pipes for data transfer, this can greatly improve network performance.
  • Limited processing on the server—With the fact that only the necessary data is sent to the server, the server is not required to process all form elements. By sending only the necessary data, there is limited processing on the server. There is no need to process all form elements, process the viewstate, send images back to the client, and no need to send a full page back to the client.
  • Responsiveness—Because Ajax applications are asynchronous on the client, they are perceived to be very responsive.
  • Context—With a full postback, the user may lose the context of where they are. The user may be at the bottom of a page, hit the Submit button, and be redirected back to the top of the page. With Ajax there is no full postback. Clicking the Submit button in an application that uses Ajax will allow the user to maintain their location. The user state is maintained, and the user is no longer required to scroll down to the location that he or she was at before clicking Submit.

Technologies That Make Up Ajax

  • XmlHttpRequestXmlHttpRequest allows the browser to communicate to a back-end server. This object allows the browser to talk to the server without requiring a postback of the entire web page. With Internet Explorer, this capability is provided by the MSXML ActiveX component. With the Mozilla Firefox and other web browsers, this capability is provided by an object literally called XmlHttpRequest. The XmlHttpRequest object is modeled after the MSXML component. The client-side JavaScript libraries hide the differences between the various browser environments. Sometimes these communications are done through a hidden FRAME or IFRAME.
  • JavaScript—JavaScript provides the capabilities to communicate with the back-end server. The JavaScript must be version 1.5 or later. Although JavaScript is not specifically required, it is needed from the standpoint that JavaScript is the only client-side scripting environment supported across the major modern web browsers. There are other client script languages; however, these are not supported across all browsers.
  • DHTML/DOM support—The browser must support the ability to dynamically update form elements, and the ability to do this in a standard way comes through the support for the Document Object Model (DOM). By supporting the DOM, it becomes easy for developers to write a single piece of code that targets multiple browsers.
  • Data transport with XML or JSON—Using XML allows for the ability to communicate with the web server in a standard mechanism. There are situations where the JavaScript Object Notation (JSON) is used as the communication notation instead of straight XML.

XMLHttpRequest Object

The XMLHttpRequest object forms the main basis for most Ajax-style applications. It acts as the main component to facilitate asynchronous requests to the server and to perform server-side processing without a traditional postback. This is to avoid the traditional postback delay for the user and enhance the user experience dramatically.

XMLHTTP is a protocol that is designed to package data as XML and send it via the network to a specific destination, or endpoint. This information is typically processed in some way, and the result is returned to the caller. The XMLHttpRequest object is an object that is implemented by most modern browsers to facilitate this communication protocol.

It was available in a limited form within Internet Explorer 4.0 but really became usable as an ActiveX object within Internet Explorer 5.0.  Unfortunately, the support across different browsers is not seamless, but neither is it a major obstacle. To use this object in the Safari, Mozilla, and some other non-Microsoft browsers, you can create an object using JavaScript with the following syntax:

var xmlHttpObj = new XMLHttpRequest();

Creating the same object in Microsoft Internet Explorer requires creating an ActiveX object, as shown here:

  var xmlHttpObj = new ActiveXObject(“Microsoft.XMLHTTP”); or

     var xmlHttpObj = new ActiveXObject(“Msxml2.XMLHTTP”);

Checking Browser Type to Determine How to Construct the XMLHttpRequest Object

if (window.XMLHttpRequest)        
 xmlHttpObj = new XMLHttpRequest();      
xmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");         

catch (e)         
xmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");        

Synchronous Requests

Take a look at a following simple code example of a synchronous operation and then take a look at the explanation of exactly what is occurring that follows.

function MakeXMLHTTPCall()

var xmlHttpObj;        
 xmlHttpObj = CreateXmlHttpRequestObject();           
if (xmlHttpObj)         
{  "GET","http://" + + 
"/XmlHttpExample1/DataFile.xml", false);          
alert("Request/Response Complete.");        

How It Works

The preceding code sample is very simple, however it does show the basic usage of the XMLHTTP object. If you examine the code in detail, you’ll see the following:

  1. First you create a new XMLHTTP object and assign it to a variable.
  2. After checking if the object is not null, that is, that the object creation in Step 1 was successful, you execute the open method passing in three parameters:“GET”,”http://&#8221; + + “/XmlHttpExample1/DataFile.xml”, false);

 The first parameter, “GET“, is the type of request to make (this can be any of the standard HTTP verbs “GET“, “POST“, “PUT“, or “HEAD“)

 The second parameter is the server address, or endpoint, to make the request to. In this case, it’s an XML file located at http://www.localhost/XmlHttpExample1DataFile.xml.

 The third parameter, false, indicates whether a synchronous or asynchronous request should take place. In this case, false indicates that a synchronous request should occur.

  1. The send method is executed on the XMLHTTP object instance to perform the actual request.


  1. Since you specified that a synchronous operation should occur, the next alert statement to display a message box is not shown until the request has completed executing and returns from the server.

alert(“Request/Response Complete.”);

Asynchronous Requests

Examine the code that follows, which performs exactly the same operation as the previous example, but operates in an asynchronous manner.

function MakeXMLHTTPCall()      
var xmlHttpObj;          
xmlHttpObj = CreateXmlHttpRequestObject();          
if (xmlHttpObj)         
{  "GET","http:// " + +     
 "/XmlHttpExample1/DataFile.xml", true);           
xmlHttpObj.onreadystatechange = function()           
if ( xmlHttpObj.readyState == READYSTATE_COMPLETE )             
alert("Request/Response Complete");            

How It Works

There are two main differences in this example as compared to the initial synchronous example:

"GET","http://" + +      
"/XmlHttpExample1/DataFile.xml", true);

The first difference is the use of the true parameter as the last argument to the open method to indicate that the request should be executed in an asynchronous manner.

The second difference is the use of the onreadystatechange event and the readyState property value. The code:

     xmlHttpObj.onreadystatechange = function()

assigns a function or event handler to the onreadystatechange event. When the state of the object changes, this event is triggered and the function is executed. The code:

     if ( xmlHttpObj.readyState == READYSTATE_COMPLETE )

checks the state of the object to determine if any action should be taken. The ready state of the XMLHttpRequest object actually contains a numeric value representing its state. The numeric value being checked for in the preceding example is a value of 4, which is represented by the variable READYSTATE_COMPLETE. The valid list of XMLHttpRequest ready states is listed in the following table:

Value Description
0 Uninitialized
1 Loading
2 Loaded
3 Interactive
4 Complete

Using the responseText Property

The responseText property is the simplest of the methods to utilize data from the response. All data that is part of the response is returned as a single string. This property is useful for simple operations where only a singular piece of data is returned and manipulated or displayed by the page.

 Returning Response Data as a String

  <script type="text/javascript" src="CommonAJAXLibrary.js">
<script type="text/javascript">
function MakeXMLHTTPCall(){              
var xmlHttpObj = CreateXmlHttpRequestObject();              
if (xmlHttpObj)              
{         "GET","http://" + +      
"/XmlHttpExample1/DataFile.xml", true);                  
xmlHttpObj.onreadystatechange = function() {                      
if ( xmlHttpObj.readyState == READYSTATE_COMPLETE )                      {              
// Extract the response text here and place in the div element.      document.getElementById("divResults").childNodes[0].nodeValue =      xmlHttpObj.responseText;                      


ASP.NET Atlas is a package of technologies including some script libraries that get deployed to the client and that implement a number of common functions and programming features for you. You simply need to include them in your JavaScript scripts, and you are good to go. Perhaps more important, it also includes web server controls that, when used on a web page, generate HTML and JavaScript that run on the browser. Through the use of web server controls, the developer can orchestrate which JavaScript code gets delivered to the client without actually doing much hand-coding—the server-side ASP.NET controls generate the HTML and JavaScript.

ASP.NET 2.0 server controls are a fundamental part of the ASP.NET framework. At their core, server controls are classes in the .NET Framework that represent visual elements on a web form. Some of them are straightforward and map closely to standard HTML tags, effectively providing server-side implementations of those tags. Others are larger-scale abstractions that encapsulate complex GUI tasks such as grids but represent them using HTML. It’s important to note that applications using server controls are rendered in the browser. Specifically, the server, using the control, compiles its logic and representation in HTML and/or JavaScript that gets delivered to the browser to render.

 Atlas Architecture

The Atlas architecture consists of two major pieces. First is the Atlas client script library, which makes it more productive for you to build the client-side functionality of your web applications. It has a rich component model and allows for object-oriented scripting. It provides many classes that add value to your applications, including network access, user interface enhancements, behaviors, actions, string manipulation, and more. It also provides an XML-based scripting platform with which you can declaratively put together client-side behavior. You can use it to map actions, behaviors, and data-binding functionality to your applications. Because it is based on XML and is declarative, it will provide the future basis for visual tools to generate Ajax UIs for Atlas.

Second is the set of server extensions; these extensions allow you to integrate the application model between the client and the server. You can use existing ASP.NET applications and target the Atlas runtime on the client.

From a programming standpoint, Atlas may be considered to be at least a couple key things:

  • Ajax library—The part of Atlas that has programmers talking the most is the support for Ajax. With this support, Microsoft has created a library to support the ability to communicate back to the server without the need to perform a full postback from the client to the server.
  • Client-side components—The ASP.NET framework has typically supported the creation of ASP.NET server-side controls. Atlas introduces the concept of client-side components and the ability to create client-side components. Along with those components is an object-oriented paradigm on the web client that includes support for inheritance, interfaces, and such items normally considered to be a part of any modern programming language.

Major Components

Atlas consists of a set of files. These files are:

  •  A server-side assembly (.dll). This assembly is named Microsoft.Web.Atlas.dll.
  •  A server-side WebResource.axd HTTP handler. This file handles streaming the appropriate JavaScript files down to the client. The content of the JavaScript that is streamed to the client is based on the functionality specified in the ScriptManager control, which is a control that will be introduced later in this chapter.
  •  The JavaScript files that are streamed to the client are embedded within the WebResource.axd HTTP handler. In addition, a set of standalone JavaScript files is also installed. These files are the same as those that are processed in the WebResource.axd file.

Server Support

The server-side support for Atlas is provided by the Microsoft.Web.Atlas.dll. This assembly provides support for the Microsoft.Web.* family of namespaces. Within these namespaces is support for controls, serialization of data, and for communicating with web services.

The WebResource.axd HTTP handler handles sending the appropiate JavaScript files down to the client.

JavaScript Files

As mentioned earlier, there is a set of JavaScript files that come with Atlas. These files are as follows:

  • Atlas.js—The Atlas.js file contains the core set of Atlas functionality. For example, the Sys namespace is defined within this file.
  • AtlasCompat.js—The AtlasCompat.js file provides the majority of the browser compatibility layer. This file contains support for Internet Explorer, Mozilla, and Safari.
  • AtlasCompat2.js—The AtlasCompat2.js file provides additional support for other browsers.
  • AtlasFX.js—This file contains support for gadgets.
  • AtlasRuntime.js—The AtlasRuntime.js file is for performing Ajax-only communication to the server without the need for all of the other files and associated overhead.
  • AtlasUIDragDrop.jsAtlasUIDragDrop.js provides the Drag and Drop API for Atlas. In addition, there are a few behaviors that are included.
  • AtlasUIGlitz.js—The AtlasUIGlitz.js file contains support for special UI and visual effects. This includes classes that support UI features such as opacity and animation.
  • AtlasUIMap.js—The AtlasUIMap.js file provides support for the Virtual Earth Atlas control.
  • AtlasWebParts.js—The AtlasWebParts.js file provides support for Web Parts in Atlas.
  • GadgetRuntime.js—The GadgetRuntime.js file provides support for gadgets in Atlas.

Adding Atlas Support with the ScriptManager Control

Now that you have down some of the basics of Atlas, you can turn to the question of how you add Atlas support to a web page.

The ScriptManager control is the mechanism for adding Atlas support to an .aspx page. Basically, the scripts needed are added to an .aspx page by using the ScriptManager control. So, to add the basic support for Atlas (Atlas.js), the following code is used:

     <atlas:ScriptManager ID="Script1" runat="server" />

The next step is to add support for calling a specific web service. This is done by adding a service to the ScriptManager control:

     <atlas:ScriptManager ID="Script1" runat="server">
             <atlas:ServiceReference Path="WebService.asmx" />

Communicating with Web Services

Calling out to an ASP.NET web service is an important part of Atlas. By default, JavaScript running within a web browser does not know how to communicate with a web service. A web service is built with C#, Visual Basic .NET, or some other language. To communicate with a web service, JavaScript must know how to call a web service, and this is done by generating JavaScript proxies using a feature of Atlas.

Generating the JavaScript Proxies

To generate the JavaScript proxies, you need to add a reference to a web service. Along with that reference, the web service methods must be exposed. This is done automatically when a JavaScript library is added as a service through the ScriptManager control. For example, the ScriptManager produces the following JavaScript code when you add a reference to the WebService.asmx file.

This code is the source code on the web page:


The preceding code will generate the output that follows on the client browser:

     <script type="text/xml-script">
   <page xmlns:script="">
           <add src="WebService.asmx/js" />
         <components />

This code shows how an external web service proxy is generated. The /js switch instructs the Atlas runtime to create a proxy object. This proxy object will also run on the client.

When you use the previous code, the following JavaScript proxy is generated and loaded on the client:

     var WebServiceTest = { path: "/Chapter10Sample/WebService.asmx",
     GetProjects:function(onMethodComplete, onMethodTimeout, onMethodError)
     {return Web.Net.ServiceMethodRequest.callMethod(this.path, "GetProjects",{},
     onMethodComplete, onMethodTimeout, onMethodError); } }

The following is the web service that will be called by the client and will run on the server:

 using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
             /// <summary>
            /// Summary description for WebService
            /// </summary>
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebServiceTest : System.Web.Services.WebService {
public WebServiceTest () {
//Uncomment the following line if using designed components
private string strCn = "......... ";
public DataTable GetProjects()
 string  strSql = "select * from tblProject";
SqlConnection  sqlCn = newSqlConnection(strCn);
SqlDataAdapter  sqlDa = newSqlDataAdapter(strSql, sqlCn);
DataSet  dsData = newDataSet ();
//throw (new ApplicationException("Error on the server."));
 sqlDa.Fill(dsData, "tblProject");
if(sqlCn.State != ConnectionState.Closed)
sqlCn = null;
sqlDa = null;

One thought on “ASP.NET AJAX

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s