Ajax Cascading Dropdown

Mohammed Imtiyaz Dec 28, 2014

Demo

Ajax Cascading Dropdown

Introduction

This article will explain you how to work with ASP.Net Ajax Control Toolkit Cascading Dropdown in ASP.Net Web Application.

Here we’ll take three Ajax Cascading Dropdown along with three corresponding ASP.Net DropDownlist which will populate data from SQL Database using web services and web methods.

When the page loads, list of countries will populate. On selecting any country, the respective states will populate and on choosing any state, their respective cities will populate.

Working with Ajax Cascading Dropdown

Step 1

Create a database “db_ajaxCascadingDropdown”. You can find the Database Script file in Database Folder. Just execute that file; the database will be automatically created.

Database Structure

Create database tables as appeared in the picture below

Ajax Cascading Dropdown

Step 2

Register Ajax Control Toolkit Library on the web page.

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

Step 3

Add Ajax ToolkitScriptManager on the web page

<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajax:ToolkitScriptManager>

Step 4

Add Ajax Cascading Dropdown control next to ASP.Net DropDownList control in the ASP.Net Web Page

aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" EnableEventValidation="false" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Ajax Cascading Dropdown</title>
</head>
<body>
    <form id="frmAjaxCascadingDropdown" runat="server">
        <ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </ajax:ToolkitScriptManager>
        <div>
            Select Country:
            <asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>
            <ajax:CascadingDropDown ID="CountryCascading"
                runat="server"
                Category="Country"
                TargetControlID="ddlCountry"
                LoadingText="Loading Countries..."
                PromptText="Select Country"
                ServiceMethod="BindCountryDropdown"
                ServicePath="DropdownWebService.asmx">
            </ajax:CascadingDropDown>

            Select State:
            <asp:DropDownList ID="ddlState" runat="server"></asp:DropDownList>
                <ajax:CascadingDropDown ID="StateCascading"
                runat="server"
                Category="State"
                TargetControlID="ddlState"
                ParentControlID="ddlCountry"
                LoadingText="Loading States..."
                PromptText="Select State"
                ServiceMethod="BindStateDropdown"
                ServicePath="DropdownWebService.asmx">
            </ajax:CascadingDropDown>
                
            Select City:
            <asp:DropDownList ID="ddlregion" runat="server"></asp:DropDownList>
                <ajax:CascadingDropDown ID="RegionCascading"
                runat="server"
                Category="Region"
                TargetControlID="ddlregion"
                ParentControlID="ddlState"
                LoadingText="Loading Cities..."
                PromptText="select"
                ServiceMethod="BindCityDropdown"
                ServicePath="DropdownWebService.asmx">
            </ajax:CascadingDropDown>
        </div>
    </form>
 </body>
 </html>

Step 5

Add WebService file ( DropdownWebService.cs )

using System;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Collections.Specialized;
using AjaxControlToolkit;
using System.Configuration;
using System.Data; 

/// <summary>
/// Summary description for DropdownWebService
/// </summary>

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]

public class DropdownWebService : System.Web.Services.WebService
{
   SqlConnection objConn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
   SqlCommand objCmd;
   SqlDataAdapter objDa;
   DataSet objDs; 

   [WebMethod]
    public CascadingDropDownNameValue[] BindCountrydropdown(string knownCategoryValues, string category)
    {
        objConn.Open();
        objCmd = new SqlCommand("SELECT country_id_pk, country_name FROM tbl_country", objConn);
        objDa = new SqlDataAdapter(objCmd);
        objCmd.ExecuteNonQuery();
        objDs = new DataSet();
        objDa.Fill(objDs);
        objConn.Close();
        List<CascadingDropDownNameValue> countryDetails = new List<CascadingDropDownNameValue>();

        foreach(DataRow dtRow in objDs.Tables[0].Rows)
        {
           string strCountryId = dtRow["country_id_pk"].ToString();
           string strCountryName = dtRow["country_name"].ToString();
           countryDetails.Add(new CascadingDropDownNameValue(strCountryName,strCountryId));
        }
        return countryDetails.ToArray();
    } 

   [WebMethod]
   public CascadingDropDownNameValue[] BindStatedropdown(string knownCategoryValues, string category)
   {
       int intCountryId;
       StringDictionary countryDetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
       intCountryId = Convert.ToInt32(countryDetails["country"]);
       objConn.Open();
       objCmd = new SqlCommand("SELECT state_id_pk, state_name FROM tbl_state WHERE country_id_fk = @country_id", objConn);
       objCmd.Parameters.AddWithValue("@country_id", intCountryId);
       objCmd.ExecuteNonQuery();
       objDa = new SqlDataAdapter(objCmd);
       objDs = new DataSet();
       objDa.Fill(objDs);
       objConn.Close();
       List<CascadingDropDownNameValue> stateDetails = new List<CascadingDropDownNameValue>();

       foreach (DataRow dtRow in objDs.Tables[0].Rows)
       {
           string strStateId = dtRow["state_id_pk"].ToString();
           string strStateName = dtRow["state_name"].ToString();
           stateDetails.Add(new CascadingDropDownNameValue(strStateName, strStateId));
       }
       return stateDetails.ToArray();
   }

   [WebMethod]
   public CascadingDropDownNameValue[] BindCityDropdown(string knownCategoryValues, string category)
   {
       int intStateId;
       StringDictionary stateDetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
       intStateId = Convert.ToInt32(stateDetails["state"]);
       objConn.Open();

       objCmd = new SqlCommand("SELECT city_id_pk, city_name FROM tbl_city WHERE state_id_fk = @state_id", objConn);
       objCmd.Parameters.AddWithValue("@state_id", intStateId);
       objCmd.ExecuteNonQuery();
       objDa = new SqlDataAdapter(objCmd);
       objDs = new DataSet();
       objDa.Fill(objDs);
       objConn.Close();
       List<CascadingDropDownNameValue> cityDetails = new List<CascadingDropDownNameValue>();

       foreach (DataRow dtRow in objDs.Tables[0].Rows)
       {
           string strCityId = dtRow["city_id_pk"].ToString();
           string strCityName = dtRow["city_name"].ToString();
           cityDetails.Add(new CascadingDropDownNameValue(strCityName, strCityId));
       }
       return cityDetails.ToArray();
   }
}

Note: Sometime we come across the situation where we need to disable CascadingDropDown. We cannot disable CascadingDropDown from CodeBehind (C# or VB). In this case, we need to write JavaScript after title tag as follows
Note: Add "BehaviorID" attribute to CascadingDropDown to be used in JavaScript.

JavaScript

<script lang="javascript" type="text/javascript">
    //This function is used to disable DropDownList (ddlCountry, ddlState & ddlregion)
    function pageLoad(sender, args) {
        $find("BidCountry").add_populated(onPopulated);
        $find("BidState").add_populated(onPopulated);
        $find("BidRegion").add_populated(onPopulated);
    }

    //Note: BidCountry, BidState, BidRegion & BehaviorID of
    //CascadingDropDown (CountryCascading, StateCascading & RegionCascading) respectively.
    function onPopulated() {
        $get('<%= ddlCountry.ClientID %>').disabled = true;
        $get('<%= ddlState.ClientID %>').disabled = true;
        $get('<%= ddlregion.ClientID %>').disabled = true;
    }
</script>