In the spirit of promoting rapid application development, jQuery -- the popular open source, cross-browser JavaScript library -- simplifies event handling, creating animations, and developing Ajax-enabled web pages. This article explains how one can use Ajax and jQuery to create Ajax-enabled controls in ASP.NET and use them in applications.
Prerequisites
To work with the code examples illustrated in this article, you should have Visual Studio 2008 and the jQuery Library installed in your system. Alternatively, you can just have Visual Studio 2010 installed because it ships with jQuery. You can download the jQuery library from the download page.
Using jQuery with ASP.NET Ajax
In this section we will implement an ASP.NET Ajax application that demonstrates how to call a Web handler using Ajax and jQuery and how to retrieve JSON data to populate a DropDownList control dynamically.
- Open the Visual Studio 2010 IDE.
- Click "File->New-Project" to create a new ASP.NET project.
- Select "ASP.NET Empty Web Application" from the list of project templates .
- Specify a name for the project and save it.
- Create a folder called "scripts" and place the jQuery library files there.
- Right-click on the project in the Solution Explorer.
- Select "Add-New Item".
- Select "Blank Web Form" and specify the name as "Default.aspx".
- Set this webform as the start page.
- Select "Add-> New Item".
- Select "Generic Handler" from the list of templates .
- Name it "CustomHandler.ashx" and click "Add" to save it.
Now that the stage is set, we will go ahead and customize the HTTP handler and the user interface. But what are Web handlers? Well, Web handlers are classes you use to handle particular requests for resources.
Here's the syntax for defining a Web handler:
The default markup code of this handler looks like this:
By default, here's how the code-behind file of this handler would look like:
13. Replace the code inside the ProcessRequest()
method with this code snippet:
14. Create a RadioButtonList and a DropDownList control. Populate the ListItems of the RadioButtonList control as shown in the code snippet below:
And, we are done! The next step is to call the HttpHandler from jQuery through an Ajax call and retrieve JSON data.
Calling the HttpHandler from jQuery
To call the Web handler from jQuery, declare an onchange
event for the DropDownList control and make Ajax calls to the server so as to fetch data in JSON format. Here's what you would need to write in your <script>
block:
This code would:
- invoke the handler
- call CustomHandler, the
ProcessRequest()
method of the HttpHandler (The source code of theProcessRequest()
method of our HttpHandler was provided earlier in this article.) - populate the JSON data and return as Response