How to Create Cascading DropDownList in ASP.NET using JQuery

No.of Views9532
Bookmarked0 times
Downloads 
Votes1
By  RRaveen   On  07 Dec 2010 08:12:30
Tag : JQuery , List Controls
The JQuery is powerful client side JavaScript library. Today I’m going to show you how to create cascading DropDownList using JQuery with JSON in ASP.NET.I hope you are all heard about cascading DropDownList and how to use with AJAX tool kit
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

The 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

Design

In 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.

Implementation

Step 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 

Image Loading

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. 

Image Loading

Make sure values response returning from the server

This 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,

Image Loading

Live Demo

Cascading DropdownList live demo

Download Sample Project

Download source files -4 kb

Conclusion

Through 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.

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
    In this article I will demonstration to how to validate whether to check at least one checkbox is checked in the Gridview in ASP.NET using JQuery. The JQuery is significant library to manipulate client html and css with less line of code.Before Jquery come up we have used the pure JavaScript to implement this features. I will give the JavaScript code as well in end of this article.
    Published Date : 30/Dec/2010
    Today I have implemented to my project to check and uncheck all checkboxes within gridview in asp.net. So in this article we focus how to implement this features using JQuery with less code. And also I have given live demonstration as well you can try it in live.
    Published Date : 29/Dec/2010
    In this article, I will explain how to sort custom objects array using JQuery. Let’s say you have array with custom objects, the custom object has few attributes as well, so in this case, you may need to sort objects with different order with specific attributes.
    Published Date : 12/Jan/2011
    The JQuery is powerful library to manipulate client side HTML, CSS, object and etc. On this article I will explain how to sort element within array using JQuery. In this demonstration I will show sort for string and numeric elements.
    Published Date : 11/Jan/2011
    Today I have introduced the new features for CodeGain article submit page to count characters for description textbox with JQuery on time. The character counter is support to users to display how many characters have entered and how many chars remaining in live.
    Published Date : 25/Dec/2010
Comments
By:AuthorDate Of Posted:4/20/2011 11:30:41 PM
To Kalidas
Hi Kalidas, Your are super hero. thank you for finding.i will update code and page asap. thank you once again and visit codegain and share this article wherever you can.
By:kalidas panamborDate Of Posted:3/30/2011 1:15:04 AM
Hello Raveen
Thanks , A very good example of cascading dropdown.I have suggestion on the code public partial class subcatelist , when we append the text in the stringbuilder the extra ',' seems to be culprit which avoids running the code in internet explorer.I think you need to add subcategories.Remove(subcategories.ToString().Length - 1, 1);
By:Iv�n TrujilloDate Of Posted:2/18/2011 9:30:26 AM
Hi there
Hi there, firstly I want to thank you for you article, it's very interesting. And I'd like to ask you about a very common issue with this kind of pages where by using javascript you add new items to a drop down list or even remove them and the server side doesn't aware about the change, so when the page posts back the code behind (.net) is just able to access the options which were rendered in the previous render. Well, my question is when you said "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)" were you reffering to this behaviour? if so, how do you avoid it? or maybe do you know a work arround for this. Raveen, thank you very much for your attention and help. Kind regards.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top