//, JavaScript/Client Side Data Binding Using jQuery

Client Side Data Binding Using jQuery

Introduction to jQuery

What is jQuery?
jQuery is an open source JavaScript library that enables you to manipulate DOM content in your web pages seamlessly. It was released in 2006 by John Resig. Since that time, it has become widely popular the world over and amongst the web application development community.

The official jQuery web site (http://jquery.com) states, “jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript code”. Numerous plug-ins of jQuery are available now. Also, the jQuery library can be extended easily using these plug-ins. Microsoft has already integrated jQuery with its Visual Studio 2010 release.

Key Features of jQuery

Here is the list of some of the key features of jQuery:

  • Browser independence: jQuery is a widely used JavaScript library that is supported by most of the modern day web browsers.
  • Simplified Event Handling model: The jQuery Event Handling model is simple and easy to use and is consistent across all modern day web browsers.
  • Extensibility: The jQuery library is extensible through the usage of its plug-in API.

Where can I get jQuery?
You can also download the jQuery library from: http://docs.jquery.com/Downloading_jQuery

Pre-requisites

To get started with jQuery with Visual Studio you should have the following installed in your system:

  • Visual Studio 2008 with SP1
  • Visual Studio 2008 jQuery Plug-in
  • jQuery Library

Alternatively, you can just use Visual Studio 2010 Beta 2 – jQuery ships free with Visual Studio 2010.

Data binding using jQuery

Data binding is the name given to the technique of binding data to data controls in ASP.NET. The controls that can be bound to data are known as data controls. In this section we will discuss how we can bind data at the client side using the jQuery library.

To get started with jQuery you can create a folder with the name Scripts in your solution explorer. You then need to place the jQuery file and its documentation file inside the folder. Once you do this, you can use jQuery in your web forms with ease. Create any webform and drag and drop the jQuery file from the Scripts folder you just created onto it. This would create the necessary reference to the jQuery library in your webform.

<script src=”Scripts/jquery-1.2.6.js” type=”text/javascript”></script>

And that you have the jQuery documentation file in the path as well, jQuery intellisense would work perfectly as well.

Implementing the Sample Application

In this section we will implement a generic handler and then use it to bind data to a DropDownList control using jQuery.
Here is the list of the steps you need to follow to implement this application:

  1. Open Visual Studio
  2. Create a New Web Application Project and save it with a name
  3. Create a Generic Handler and save with the name TestHandler

Web Handlers are classes those are responsible for handling specific requests for resources. Web Handlers are placed in files that have an extension of .ashx. Here’s how you define a Web Handler:

<%@ WebHandler attribute=”value” [attribute=”value”…] %>

You can know more on Web Handlers here: http://msdn.microsoft.com/en-us/library/ms366713.aspx
The markup code of the generic handler we just created is shown below:

<%@ WebHandler Language=”C#” CodeBehind=”TestHandler.ashx.cs” Class=”TestHandler” %>

The code behind for the generic handler you just created would look like as shown below:

using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = “text/plain”;
context.Response.Write(“Hello World”);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}

Replace the code in the ProcessRequest() method in your generic handler with the one given below:

public void ProcessRequest(HttpContext context)
{
String strTypeID = context.Request.QueryString[“typeID”];
StringBuilder sbName = new StringBuilder();
switch (strTypeID)
{
case “1”:
sbName.Append(“[“);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”DELL\”,”);
sbName.Append(“\”TypeID\”:\”1\””);
sbName.Append(“},”);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”Compaq\”,”);
sbName.Append(“\”TypeID\”:\”1\””);
sbName.Append(“}”);
sbName.Append(“]”);
break;
case “2”:
sbName.Append(“[“);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”HCL\”,”);
sbName.Append(“\”TypeID\”:\”2\””);
sbName.Append(“},”);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”Wipro\”,”);
sbName.Append(“\”TypeID\”:\”2\””);
sbName.Append(“}”);
sbName.Append(“]”);
break;
}
context.Response.ContentType = “application/json”;
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(sbName.ToString());
context.Response.End();
}

Here is how the complete source of the TestHandler.ashx.cs file looks like now:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Text;

[WebService(Namespace = “http://tempuri.org/”)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
String strTypeID = context.Request.QueryString[“typeID”];
StringBuilder sbName = new StringBuilder();
switch (strTypeID)
{
case “1”:
sbName.Append(“[“);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”DELL\”,”);
sbName.Append(“\”TypeID\”:\”1\””);
sbName.Append(“},”);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”Compaq\”,”);
sbName.Append(“\”TypeID\”:\”1\””);
sbName.Append(“}”);
sbName.Append(“]”);
break;
case “2”:
sbName.Append(“[“);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”HCL\”,”);
sbName.Append(“\”TypeID\”:\”2\””);
sbName.Append(“},”);
sbName.Append(“{“);
sbName.Append(“\”BrandName\”:\”Wipro\”,”);
sbName.Append(“\”TypeID\”:\”2\””);
sbName.Append(“}”);
sbName.Append(“]”);
break;
}
context.Response.ContentType = “application/json”;
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(sbName.ToString());
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}

Next we need to design a user interface where we will take a RadioButtonList control and a DropDownList control.  As and when the selection in the RadioButtonList  changes, the DropDownList would be dynamically populated with content using jQuery.

Here is how the markup code for these controls would look like:

<table>
<tr>
<td>
<asp:RadioButtonList ID=”rbList” runat=”Server” ToolTip=”–Select Type –“>
<asp:ListItem Text=”Laptops” Value=”1″></asp:ListItem>
<asp:ListItem Text=”Desktops” Value=”2″></asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td>
Brand Name:
</td>
<td>
<asp:DropDownList ID=”ddlBrand” runat=”server”>
</asp:DropDownList>
</td>
</tr>
</table>

The following jQuery code snippet illustrates how you can call the generic handler created earlier in the client side using jQuery:

$(document).ready(function() {
$(“#rbList”).change(function() {
$(“#ddlBrand”).html(“”);
var TypeID = $(‘input[name=rbList]:checked’).val();

if (TypeID != 0) {
$.getJSON(‘TestHandler.ashx?typeID=’ + TypeID, function(getBrands) {
$.each(getBrands, function() {
$(“#ddlBrand”).append($(“<option></option>”).val(this[‘TypeID’]).html(this[‘BrandName’]));
});
});
}
});
});

And, here’s the complete markup code for your reference:

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”Test._Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Data Binding in jQuery</title>

<script src=”Scripts/jquery-1.2.6.js” type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function() {
$(“#rbList”).change(function() {
$(“#ddlBrand”).html(“”);
var TypeID = $(‘input[name=rbList]:checked’).val();
if (TypeID != 0) {
$.getJSON(‘TestHandler.ashx?typeID=’ + TypeID, function(getBrands) {
$.each(getBrands, function() {
$(“#ddlBrand”).append($(“<option></option>”).val(this[‘TypeID’]).html(this[‘BrandName’]));
});
});
}
});
});
</script>
</head>

<body>
<form id=”frmjQuery” runat=”server”>
<div>
<table>
<tr>
<td>
<asp:RadioButtonList ID=”rbList” runat=”Server” ToolTip=”–Select Type –“>
<asp:ListItem Text=”Laptops” Value=”1″></asp:ListItem>
<asp:ListItem Text=”Desktops” Value=”2″></asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td>
Brand Name:
</td>
<td>
<asp:DropDownList ID=”ddlBrand” runat=”server”>
</asp:DropDownList>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Screenshots and Summary

When you execute the application, the output would be similar to what is shown in the figure shown below:

Note that the DropDownList control is dynamically populated as and when the selection in the RadioButtonList control changes. Now, select the “Desktops” option and you can see the data in the DropDownList change again. Here is how the data in the DropDownList control would now look like:

References

Summary

In this article we examined data binding using jQuery and JSON. You can also use jQuery with Client Side Data Binding Templates without the need to write too many lines of JavaScript code.

You can take a look at this article:
http://weblogs.asp.net/dwahlin/archive/2009/04/17/minimize-code-by-using-jquery-and-data-templates.aspx

Also, here is another awesome post by Rick Strahl on client side:
http://www.west-wind.com/Weblog/posts/509108.aspx

In future articles in this series of articles on jQuery, we will take a look at the other powerful features of jQuery.

2010-05-27T23:28:24+00:00 February 12th, 2010|ASP, JavaScript|0 Comments

About the Author:

Microsoft Most Valuable Professional Winner of Community Credit Awards at www.community-credit.com Selected as MSDN Featured Developer of the Fortnight in November and December, 2008 Author of the following books: ASP.NET 4.0 Programming (Mc-Graw Hill Publishing) Entity Framework Tutorial (Packt Publishing) Pro Sync Framework (APRESS) Sams Teach Yourself ASP.NET Ajax in 24 Hours (Sams Publishing) ASP.NET Data Presentation Controls Essentials (Packt Publishing) Blog: http://aspadvice.com/blogs/joydip/default.aspx

Leave A Comment