AJAX basics with jQuery in ASP.NET

ASP.NET now has support for the jQuery JavaScript library. Although ASP.NET integrated AJAX technology by introducing the is the UpdatePanel server control, jQuery offers an alternative, and more versatile, way of doing it and a great deal more besides. Matteo shows how easy it is to get started with using jQuery.

A Step Ahead of the UpdatePanel

This article will show you how AJAX can be used on ASP.NET web pages by means of the increasingly popular JQuery (JavaScript) library. It will explain how to use jQuery for this, and what the advantages are of using it.

In the last few years, we have seen an increasing interaction between the user and the web sites as a result of the design and technology ideas that we refer to as  Web 2.0.

Today Web 2.0 sites host, and manage, a lot of  data about their users. Web users store their data (images, video and so on) online, update it on a regular basis, share it with other users, post comments on blogs and so on. This trend has, in turn, lead to an increase in the number of round trips between clients and servers.

In the traditional Web model, users ask for a static page, the server gets it back to them and the browser then renders the page in its entirety. Then the users move on to the next page.  On a data-intensive site, this extra activity will not only increase the network traffic, but will also force the user to wait for the page to be rendered every time any data is changed.

Today, users of a Web 2.0 site will be able to request information, or make changes, and will get the information they need when parts of the page’s content is refreshed from data  supplied by the server without them having to move to another page.

The key technology for solving this problem is AJAX, a technique that allows JavaScript to make an HTTP POST or GET request to fetch, or send , data; whilst not requiring a complete refresh of the page.

So what is AJAX?

AJAX, according to Jesse Garrett who coined the term, is an acronym (Asynchronous Javascript And XML)  that combines several long-standing technologies together.

  • Using the browser’s XMLHttpRequest object to transfer data asynchronously between the client and server.
  • Using XML( or JSON) as the format for the data being transferred.
  • Using XHTML and CSS for structure and presentation.
  • Using the Document Object Model  to render information within the browser page.
  • Using Javascript to bind everything together.

The client browser uses JavaScript functions to perform a call to the server and the server responds to it asynchronously. This means that, after the client request, JavaScript in the web page continues to execute whilst it waits for a response from the server.

The overall process is made possible by using the XmlHttpRequest object. It was introduced by  Microsoft as an ActiveX component starting from Internet Explorer 5.0.  Today, all browsers have their own implementation of it.

In the traditional Browser approach to returning requested information to the user:

  1. The browser requests a page (using GET or POST method) from  the web server using the URL of the page.
  2. If the page exists, the server responds to the browser by sending to it the requested HTML page.
  3. The browser gets the page content and renders  it on its surface.

AJAX works in a quite different way.

  1. Some JavaScript code on the client begins an HTTP request to the web server by using the XmlHttpRequest object and continues with its execution.
  2. After the server has serviced the request, it passes the result back to the browser. This invokes a JavaScript function (the callback) within the client by passing to it, as arguments, the result of the execution as XML document.
  3. The callback function parses the  data and updates the page’s content.

Microsoft ASP.NET technology integrated AJAX technology by introducing the AJAX  Extension to the .NET Framework. This is based on some server controls (the principal one is the UpdatePanel control), that allows you to add AJAX capabilities to ASP.NET web forms. However, several other solutions are available that provide a more general solution to implementing AJAX across different server platforms.

AJAX libraries

As developer, you will probably only rarely need to work directly with the XmlHttpRequest object; this is because developers generally now make use of JavaScript libraries to implement JavaScript functionality on their web pages. There are many free powerful JavaScript libraries today available on the web. To name a few of them: JQuery, ExtJS, prototype, script.acoul.us, Dojo, Yahoo! UI library, Google Web Toolkit.

These  libraries make Ajax easier to use by “hiding” the hard work that is required when working with JavaScript.  If you find that you really need to access the XmlHttpRequest object directly, you will find a good guide on the Apple Developer Center on how to use it.

The use of a JavaScript library speeds up development work; even Microsoft AJAX Extensions are based on a JavaScript library. This is the Microsoft Ajax Library. The scripts files are embedded as resources on the System.Web.Extensions assembly and they are responsible to manage all the task needed to perform partial rendering with UpdatePanels .

For this article, we’ll be showing you how to use the JQuery library in preference to Microsoft AJAX Extensions.

Preparing The Server Side Code

We’ll start our work with a simple example. For it, we need to set up a data source that will be queried by the client in order to update the content of the client’s page.

We can implement a simple default.aspx web page that gets a sentence from the server when the user clicks a button. Although we’d need to show data provided by web services or WCF services (and in general RESTful services) to demonstrate the true potential of AJAX , we’ll start with a very simple example using, as our data source,  an XML document (sentences.xml) with this content:

To use our data source, we need a simple method that will open the xml file and will extract a specific sentence. For simplicity, we’ll decide  that the sentence will be randomly selected. To do so, we put on the code behind of our default.aspx page the following method:

The previous method extracts a random number between 0 and 2 by using the Random class. The number extracted is then used on the LINQ query to get the text of the randomly selected sentence. This is finally returned to the caller as simple text.

The Microsoft Ajax  Content Delivery Network (CDN)

To complete the server side code, we need to allow our ASP.NET page to use the JQuery library. We could just download the JQuery script file from the JQuery site and put it on our solution. There is a better approach.  We can use the Microsoft Ajax Content Delivery Network. The improved support of the new .NET Framework 4.0 for JavaScript libraries has even been extended to the task of downloading  JavaScript files by the client. To increase the page’s Load performance, Microsoft created a new service, called the Microsoft Ajax Content Delivery Network (CDN) that hosts a range of common resources needed by a web page on “edge cache” servers, thereby improving the page’s load-time. You can read more about the CDN on the Scott Guthrie’s blog at Announcing the Microsoft AJAX CDN

We choose the second options. We use a ScriptManager to register the JQuery library to our web page using, as source, the CDN as follow:

If you inspect the previous block of code, you will see that, to allow the utilization of the CDN, the ScriptManager on .NET Framework 4.0 implements the new EnableCdn property that must be set to true.

Traditionally, the ScriptManager was developed with the intent to provide JavaScript registration on the page when working with UpdatePanels (and with Microsoft AJAX Extensions in general). Its main purpose was to register the required  Microsoft Ajax Library’s JavaScript files on the client, getting their content from the System.Web.Extension assembly’s resources. As we see on the previous block of code, the new ScriptManager  allows you the option to disable the Microsoft Ajax Library’s scripts registration by setting to Disabled the new property AjaxFrameworkMode.  So, starting from .NET Framework 4.0, ScriptManager seems to be becoming the standard way to manage all the JavaScript code needed by our pages. In this case, we have used it to register, on the client, the JQuery library from the CDN.

Getting jQuery intellisense.

Visual Studio 2010 support for JQuery  extends to providing  intellisense  when working with this library.  Visual Studio 2010 is able to use the comments contained on a special version of the JQuery library in order to populate the intellisense window as for the standard .NET classes. To use this feature, all you need to do is to replace the .min suffix with the -vsdoc suffix on the ScriptReference declaration of the ScriptManager:


Remember to revert the -vsdoc with the .min suffix when your site will be released. This will increase the site speed by reducing the quantity of JavaScript code that the client had to download. If the .min version is a JavaScript file that occupies 69 KB on disk, the -vsdoc version has length given by 229 KB.

Writing The Client-Side Code

To allow the client to get a sentence from the server asynchronously, we first put a Button and a TextBox on the web page. We assign the btGet  value to the button’s id property and the txtSentence value to the analog TextBox’s id property.

We want a new sentence to be retrieved from the web server and then displayed inside the TextBox whenever the user clicks on the button.

The AJAX request doesn’t make use of  a postback of the page:  instead,  it uses JavaScript code to begin the request. So, we create a JavaScript function on the client and let the onclick event of the button invoke it:

The getSentence JavaScript function must contain the code needed to get a sentence form the server, using JQuery.

For this to happen, we use the .ajax() method of the main JQuery object $. This method accepts, as input, a JavaScript object that has all the elements that are needed to perform an AJAX call to the server.  We don’t need all of them and so we’ll only describe here  the most commonly used.

For a full list, see the JQuery documentation at jQuery.ajax (settings)

url: JQuery will use the XmlHttpRequest object to perform a request to the server at this url. It will use the GET method, unless a different value for the type element is specified.

data: Data can be sent to the server, either as query string attached to the url of the GET request, or in a POST request . Data must be expressed as JSON formatted object. Data  can be also be sent to the server by directly adding the query string to the url element.

success: This allows us to set the callback function that must be executed on the client after the server response is received successfully. It is used to refresh the page’s content. When called, the parameters that are passed as arguments are: (1) data, that represent the data received by the server, (2) textStatus, that is a string describing the status of the response and (3) XmlHttpRequest that represents the instance of the XmlHttpRequest object used for the request.

dataType: This specifies the type of data expected by the client. It can be ‘html’, ‘text’, ‘xml’, ‘script’, ‘json’ and ‘jsonp’. If nothing is specified, the method will try to interpret data received on the basis of the content type of the response. While html, text, and xml are obvious, the other types  need explaining.  if we use the ‘script’ value,  the method will expect some JavaScript code, if we use ‘json’ (or the less known ‘jsonp’)  value, then the method will try to convert the response into a JavaScript object.

error: This allows you to set a JavaScript callback function that will be invoked if some error occurs during the AJAX request. Its arguments are: (1) XmlHttpRequest, that represents the instance of the XmlHttpRequest object used for the request, (2) textStatus, that is a string describing the status of the response, (3) errorThrown that is a string that represent the description of the error generated.

complete:If this is set,  than the JavaScript function that you’ve specified will be invoked at the end of the process, after that the success or error function are executed. Its arguments are: (1) XmlHttpRequest that represents the instance of the XmlHttpRequest object used for the request, (2) textStatus, that is a string describing the status of the response.

Our getSentence() function will then look like this:

We have defined the callback function as an anonymous JavaScript function object and we have set the success element to its value. After the server response, this function will be invoked and its content will be executed. The function’s body shows what will happen. By using the JQuery function $, using as the selector the id of the TextBox, its value will be changed  to the value of the returned data.

If an exception occurs, the error function will be invoked, and the exception’s description will be shown on the screen. We get the error description from the third argument passed to the JavaScript function. So, it will be contained on the arguments[2] array item.

You’ll notice that we decided to specify a value for the data element. This value will be sent to the server as a query string.  This is because our design requires that we need a trick to signal, on the server side, that the request is an AJAX request rather than a normal GET request.  Remember that AJAX requests are made by invoking a server resource by using either the GET or POST method of the HTTP protocol. So If we use the GET, the ASP.NET pages are not able to distinguish an AJAX request form a standard GET request. We intercept the AJAX request by checking the query string of the same. If the request contains the key “get” on its query string, an AJAX request was made, if it doesn’t, the page will respond as for normal GETs.

So, on the OnLoad event of our web page we could write something like this:

If the query string contains a key named “get”, we know that the client is asynchronously waiting for a sentence as plain text. In this case: we (1) clear the response buffer, (2) set the content type to text/plain (so that JQuery will know how to interpret it), (3) write to the response stream the string selected with the GetSentence() method, (4) end the response.

After that, the callback function will be invoked on the client, passing the string as the value for the data argument.  As we have specified, the TextBox will be filled with the extracted value.

You can download a copy of this example at the bottom of the article in the file “SupportingDocuments”.

Using  More Complex Data

We’ve shown you, in the previous example, how to perform an AJAX request of a string to a web server and how to use it to refresh a web page. In reality, things are usually more complex. Only rarely do you have to update your page with only a simple text. Normally, a mix of data must be refreshed instead. To be able to do so, we need to understand how to pass complex data to the client and how to use it to refresh the page.

The most frequently used approach is to serialize our data using the JSON  format and send the formatted string to the client for visualization. When data reach the client (with the callback invocation made by the server), JQuery is able to transform it in a JavaScript object that we can then use to refresh the page’s content.

To illustrate this, we’ll  suppose that we want to visualize on the client not only a randomly selected sentence, but also the ID of the same. To do this, we add a second TextBox to the default.aspx page, with ID given by txtID. It will show the ID related to the sentence.

We need to modify the GetSentence method of the server in this way:

This new method selects a sentence and then creates a JSON string that contains the id of the sentence in addition to the sentence’s text. The returned string will be something like this:

Where the <extracted_id> and the <extracted_sentence> are the id and the text of the selected sentence.

The OnLoad method of the page must be modified as follows:

We have modified the content type of the response from text/plain to application/json.

Finally, we change the JavaScript callback on the client in this way:

The JQuery .ajax() method automatically transforms the JSON string into a JavaScript object , on the basis of the content type of the response, and passes it to the success function. The created JavaScript object will have two properties: the .id properties with the id of the sentence and the .sentence property with the text of the same. This structure reflects the original JSON string structure. We use the two properties to update our page.

Improving the User-Experience

If you happen to use Microsoft AJAX and UpdatePanels, you probably know that Microsoft AJAX allows you to use a control named UpdateProgress to display some HTML code on the page immediately before the AJAX request and to hide it after  it has  completed.

This allows us to display, for example, an animated gif while the user is waiting for the completion of the request.

JQuery and its AJAX implementation allow you to perform the same thing, but by using some JavaScript code just before the AJAX request and just after the callback completion.

This can improve the user-experience thanks to the fact that you can now use a more dynamic JavaScript code rather than static HTML to generate visual effects on the client.

This can be done by using the following methods implemented on the JQuery library:

.ajaxStart(fn): Allows you to set a JavaScript callback-function to execute just before the AJAX request.

.ajaxComplete(fn): Specifies a JavaScript callback-function to execute just after the AJAX request completion.

This methods are attached to each page’s element when they are selected with the main JQuery function $.

Returning to our example, we surround our two TextBoxes with a div tag: giving to it the value ‘container‘ for its id property.

Although JQuery has a rich set of elements to perform animations of any type, we simply use the .hide() method to hide the TextBoxes just before the AJAX request, and the .show() method to show them again refreshed with the new values.

We can set the two argument functions of the two methods on the .ready() method of the JQuery library. Remember that this method is executed after the completion of the loading of the page, when it is ready to operate.

Our JavaScript code will be:

If you run the application, the two TextBoxes will be hidden  after the button-click by reducing the div tag height to 0 with a speed given by the JQuery-defined value ‘normal‘. After the selection of the new sentence, the two TextBoxes will reappear on the page by resetting the height of the div tag to its original value with a speed identical to the previous.

You can download a copy of this example at the bottom of the article in the file “SupportingDocuments”.


In this article we’ve use JQuery to implement AJAX features on a web page. We have seen how easy it is to perform common AJAX tasks in JQuery (and in general JavaScript libraries that supports AJAX capabilities), because it is easier to modify those AJAX requests  without being limited to perform only a partial rendering of the page. Partial rendering allow us only to update server controls contained on some UpdatePanel. The update occurs when we change some properties of those controls on the  server side.   With AJAX libraries we are free to select any kind of data source we want. We need only to serialize them, maybe using JSON, and send them to the client.

However, this doesn’t mean that ASP.NET  UpdatePanels should not be used anymore. They are very easy to use and very quick to setup. With a simple drag and drop in Visual Studio, we have all the machinery to perform AJAX requests without having to write any other blocks of code. And this is the purpose of server controls: To make our life easier. When a server control can do it, allow it to do it, otherwise look elsewhere. And if you’re looking for more configurable AJAX work, then  jQuery is a good library to consider.