Cascading Dropdown in ASP.NET using jQuery

Cascading dropdown is the most common requirement we use to get in the real time world. So mainly beginners feel difficulty in doing this task. I have seen many of my friends and colleagues face this problem. Hope this could help those folks.

Normally some folks posting the Question "How to get the Second Dropdown fill based on the first dropdown selection?". The processing of filling the second dropdown based on the first dropdown selection is called "Cascading Dropdown or Filtered Dropdown". Actually the data source I have used is XML file which contains the Country and State. In the source code this XML file is also given please check once you download the source code.

Cascading dropdown can be done in many ways out of which i have chosen this using jQuery. I have taken the common example of Country and States. I have taken two Composite types as "Country" and "State" which contains properties as ID,Name. I have given the structure also.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingExample
{
    public class Country
    {

         public string CountryName { get; set; }
         public int CountryID { get; set; }
        
        public List<Country> FetchStates(string countryName)
         {
             return new List<Country> { };  
         }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CascadingExample
{
    public class State
    {
         public State()
        {
             //To Do
        }
         public int StateID { get; set; }
        public int CountryID { get; set; }
        public string StateName { get; set; }
    }
}

I have designed a separate class for fetching data from the data source (XML file) based on the filtering. The name of the class is given as the "Data Manager".

To present this example in a beautiful way i designed a screen as shown below:

Cascading dropdown

I have fetched the Countries list from the XML file in the Page_load of the Page and the method("FetchCountries") in the DataManager class.

public List<Country> FetchCountries()
{
      List<Country> lstCountry = new List<Country>();
      XmlDocument xDoc = new XmlDocument();
      xDoc.Load(xmlPath);
      XmlElement root = xDoc.DocumentElement;
      XmlNodeList nodeList = root.GetElementsByTagName("country");
      for (int i = 0; i < nodeList.Count; i++)
      {
           String countryName = String.Empty;
           countryName = nodeList[i].Attributes["name"].Value;
           lstCountry.Add(new Country { CountryID = i, CountryName = countryName });
      }
      return lstCountry;
}

The HTML design of the CascadingExample.aspx is given below:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CascadingDropDown.aspx.cs"
    Inherits="CascadingExample.CascadingDropDown" %>

<!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 DropDownLists With ASP.NET and jQuery</title>
    <style type="text/css">
        .ddl_style
        {
            text-align: justify;
            font-family: Verdana;
        }
        .para_Style
        {
            text-align: justify;
        }
     </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var ddl = $("select[name$=ddlCountries]");
            var ddlState = $("select[name$=ddlState]");
            ddl.focus();
            ddl.bind("change keyup", function () {
                if ($(this).val() != "-1") {
                    $('p[class$="para_Style"]')[0].innerText = "";
                    loadStates($("select[name$=ddlCountries] option:selected").val(), $("select[name$=ddlCountries] option:selected").text());
                    ddlState.fadeIn("slow");
                } else {
                    ddlState.fadeOut("slow");
                }
            });
        });
        function loadStates(selectedIndex, selectedText) {
            $.ajax({
                type: "POST",
                url: "CascadingDropDown.aspx/FetchStates",
                data: "{countryID:" + parseInt(selectedIndex) + ",countryName:'" + selectedText + "'}",
                contentType: "application/json;char-set=utf-8",
                dataType: "json",
                async: true,
                success: function Success(data) {
                    printStates(data.d);
                    selectedIndex = 0;
                    selectedText = '';
                }
            });
        }
        function printStates(data) {
             $("select[name*=ddlState]>option").remove();
            $("select[name*=ddlState]").append($("<option></option>").val(-1).html("(Please Select)"));
            $('p[class$="para_Style"]').append("You have Selected <b> " + $("select[name$=ddlCountries] option:selected").text() + "</b><br>State List is given below:<br>");
            for (var i = 0; i < data.length; i++) {
                 $("select[name*=ddlState]").append($("<option></option>").val(data[i].StateID).html(data[i].StateName));
                $('p[class$="para_Style"]').append(data[i].StateName + "<br>");
             }
        }
       
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="font-family: Verdana; text-align: left; font-size: medium; color: Green">
            An Example to show Cascading Dropdown in Asp.Net using jQuery
         </h2>
        <br />
        <table style="font-family: Times New Roman Baltic; text-align: left; font-size: medium;
            color: Red">

            <tr>
                 <td>
                     <label>
                        Select Country</label><br />
                 </td>
                 <td>
                     <asp:DropDownList ID="ddlCountries" runat="server" AppendDataBoundItems="true" CssClass="ddl_style">
                         <asp:ListItem Text="(Please Select)" Value="-1" Selected="True" />
                     </asp:DropDownList>
                 </td>
            </tr>
            <br />
            <tr>
                 <td>
                     <label>
                        Select State</label><br />
                 </td>
                 <td>
                     <asp:DropDownList ID="ddlState" runat="server" CssClass="ddl_style" AppendDataBoundItems="true">
                     </asp:DropDownList>
                 </td>
            </tr>
        </table>
        <p class="para_Style">
        </p>
    </div>
    </form>
</body>
</html>

In the Cascading Example i have designed a WebMethod and called using jQuery AJAX POST.

[WebMethod]
public static List<State> FetchStates(int countryID, string countryName)
{
      DataManager objDataManager = new DataManager();
      List<State> stateObj = new List<State>();
      stateObj=objDataManager.FetchState(new Country { CountryID = countryID, CountryName = countryName });
      return stateObj;
}

When we run the page we will get the output like this:

Cascading dropdown using jquery

To better understand this concept you need to analyse in the HTML watcher tools. The best tool what i can say is FireFox add on FireBug. If you don't have the firefox you need to download here(FireFox) and download the firebug add on here(FireBug). Now follow the steps given below

  1. Click on the Firebug which will open in the bottom.
  2. Now go to the "Net" tab where you will have different tabs like Header,Response,Post,JSON.
  3. Now select the country in the first dropdown.
  4. In the Net tab you can see in the POST tab you can see the method name as "FetchStates" which takes two input parameters as countryID and countryName.
  5. We can see clearly the response we got in the "Response" tab .

You can see in the below image:

Cascading dropdown in asp.net

ASP.NET Cascading dropdown

This is how we can do the cascading dropdown in ASP.NET using jQuery.

If any queries or suggestion regarding are welcome.

Happy Coding :-)

Up Next
    Ebook Download
    View all
    Learn
    View all