IntroductionThe JQuery is powerful client side JavaScript library. Today I’m going to show you how to create cascading dropdownlist using JQuery with JSON features in ASP.NET.I hope you are all heard about cascading dropdownlist and how to use with AJAX tool kit. more about AJAX ToolKit here DesignIn this demonstration, we have collection of categories in parent dropdown list. When we are selecting a category from the parent dropdown list, then sub category list will load into the child dropdown list. ImplementationStep 1 As usual create project with a page with two dropdown list and also add JQuery library from Google CDN in the head of the page. Note: Always use the JQuery library from Google for faster rendering pages. Html Page Html Code <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>Cascading DropDown list using JQuery and ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div style="padding: 5px;">
<div>
<h2>
This is Cascading demo Page</h2>
</div>
<div style="margin-bottom:10px;">
<span style="margin-right: 35px;">category:</span><asp:DropDownList ID="cmbcatelist"
runat="server">
<asp:ListItem Value="0" Selected="true">[ select ]</asp:ListItem>
<asp:ListItem Value="1">ASP.NET</asp:ListItem>
<asp:ListItem Value="2">C#</asp:ListItem>
<asp:ListItem Value="3">VB.NET</asp:ListItem>
<asp:ListItem Value="4">JQuery</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<span style="margin-right:5px;">Sub Category:</span><asp:DropDownList ID="cmbsubcateList"
runat="server">
<asp:ListItem Value="0" Selected="true">[ select ]</asp:ListItem>
</asp:DropDownList>
</div>
</div>
</form>
</body>
</html>Step 2 Now I’m going to add JQuery Library in head from Google CDN. <script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> Note: JQuery version 1.4.4 is latest version of the JQuery library. You can find all versions and more about JQuery here Now we have to write code for when we are select the category from the first dropdown list, get the sub categories list from the server and then add into the second dropdownlist without Postback. The purpose cascading dropdown list is minimizing/ignore the page refreshing.But we need to get the sub categories list from the server, so we could not use the current page (we can use the current page, but there is some issues, I will give those in later part of this article). Well again create another new page or handler to get the list based on the selected category code from server as formatted string response. Step 3 To this demonstration I have created a page call as “subcatelist.aspx”, we don’t need do any design on this page. Because this page just return the formatted sub category list for what is category code come from other page as query string. The subcatelist page code like will be followings, Subcatelist.aspx.cs using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
public partial class subcatelist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["cCode"] == null)
{
return;
}
string categorycode = Request.QueryString["cCode"].ToString();
System.Text.StringBuilder subcategories = new System.Text.StringBuilder();
subcategories.Append("[");
if (categorycode == "1")
{
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "How to" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "01" + "\"");
subcategories.Append("},");
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "General" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "02" + "\"");
subcategories.Append("},");
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "http handler" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "03" + "\"");
subcategories.Append("},");
}
else if (categorycode == "2")
{
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "Windows Form" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "01" + "\"");
subcategories.Append("},");
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "How to" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "02" + "\"");
subcategories.Append("},");
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "Custom Controls" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "03" + "\"");
subcategories.Append("},");
}
else
{
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "How to " + "\",");
subcategories.Append("\"Subcatecode\":\"" + "01" + "\"");
subcategories.Append("},");
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "Windows Form" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "02" + "\"");
subcategories.Append("},");
subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "Applications" + "\",");
subcategories.Append("\"Subcatecode\":\"" + "03" + "\"");
subcategories.Append("},");
}
subcategories.Append("]");
Response.ContentType = "application/json";
Response.ContentEncoding = Encoding.UTF8;
Response.Write(subcategories.ToString());
Response.End();
}
}
In above code there are many important points we have to keep mind in order parse response using JQuery JSON and then add into the child dropdownlist.
1. Formatting of the child dropdown list options subcategories.Append("{");
subcategories.Append("\"Description\":\"" + "How to " + "\","); //This is Text of the option
subcategories.Append("\"Subcatecode\":\"" + "01" + "\""); // This is value of the option
subcategories.Append("},");
You have to add each option value and text as array. {Description: Howto, Subcatecode: 01}2. Append multiple options using square brackets. [{Description: Howto, Subcatecode: 01} , {Description: General, Subcatecode: 02}]3. Seperate each option array by comma. [{Description: Howto, Subcatecode: 01} , {Description: General, Subcatecode: 02} , {Description: Windows Form, Subcatecode: 03}] ]4. The built string has to write into the response with ContentType : application/json Response.ContentType = "application/json"; 5. The set Encoding of the Response would be Encoding.UTF8 Response.ContentEncoding = Encoding.UTF8; 6. Finaly the response must be end, otherwise next request prevent or waiting by thread. Note: I’m using hard coded values for build sub category list, but you can replace values from the database. Step 4 Now come to the main page and write few line of JavaScript code to read response and append subcategories coming from the subcatelist page. JavaScript <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#cmbcatelist').change(function() {
$('#cmbsubcateList').html("");
var cateCode = $("#cmbcatelist").val();
if (cateCode != 0) {
$.getJSON('http://localhost/jprojects/subcatelist.aspx?cCode=' + cateCode, function(SubSection) {
$.each(SubSection, function() {
$("#cmbsubcateList").append($("<option></option>").attr("value", this['Subcatecode']).text(this['Description']));
});
});
}
});
});
</script>In the above script, there are few lines are important in order to work with JSON. 1. You have to call getJSON method to read response, which return from the server within the category dropdown change event. Because when you are select new category in every time in category dropdown list, server will return new response with fresh subcategory list. if (cateCode != 0) {
$.getJSON('http://' + location.host + '/subcatelist.aspx?cCode=' + cateCode, function(SubSection) {
//---
//----
}2. The SubSection variable is has actual list of the sub category list return by the server. Now we have to iterate one by one and append options into the sub category dropdown list. $.each(SubSection, function() {
("#cmbsubcateList").append($("<option></option>").attr("value",this['Subcatecode']).text(this['Description']));
});Note: If you using master page, then this method control finding return null for controls, so you have to change the code as like below to find the dropdownlist. Others are still remaining same. $("[id$=cmbcatelist]").change(function() {
// code
});Similar way has to apply other place, everywhere you are finding controls.More about find the controls with master page, please refer With Master Page section. Let's run the application and select the category from the parent dropdown list and output will like below. Make sure values response returning from the serverThis is section explain how to makes sure values are returning from the server in correct format. To this we can use the firebug extension for Firefox. More about firebug here I hope you already installed firebug extension, just click “Net” in firebug window and then click “XHR” for view the XmlRequest and Response values. The test result will be like following, Live DemoCascading DropdownList live demo Download Sample ProjectDownload source files -4 kb ConclusionThrough this article, you have learned how to create cascading dropdown list with JQuery in ASP.NET without refresh page. I hope this is help to all, if you have any comments please post. |