A short demo on how to create/use CascadingDropDown from the “AjaxControlToolkit”.

For this demo I will use the world of football since this lends itself well to cascading drop downs.

A country has leagues, a league has teams and teams have players, players have statistics etc.

 

So let’s get to it.

. First create a new “ASP.Net Empty Web Site” in Visual Studio called AjaxCDDDemo

. Install the “AjaxControlToolkit” via NuGet by right clicking the project and selecting “Manage NuGet Packages” and search online for “AjaxControlToolkit” and hit install.

 

. Then we need a web service that feeds the drop down.
From:
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/CascadingDropDown/CascadingDropDown.aspx

All the logic about the contents of the set of DropDownList controls lives on the server in a web service. This web service can use any suitable method for storing and looking up the relevant data.

So add a new Web Service called “FootballService.asmx" (using C# in this example) to the project.

 

. Then you need to uncomment the [System.Web.Script.Services.ScriptService] attribute above the class definition.

 

. You can load data from a database or any other storage. I will use three lists (Countries, Leagues, Teams) in this example. You can add more lists (Players for each team etc.) if you wish.

Full code for the web service:

 

using AjaxControlToolkit;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

 

///<summary>

/// Summary description for FootballService

///</summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

 

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]

publicclassFootballService : System.Web.Services.WebService {

 

    public FootballService () {

 

        //Uncomment the following line if using designed components

        //InitializeComponent();

 

        FillLists();

    }

 

    List<Country> countries = newList<Country>();

    List<League> leagues = newList<League>();

    List<Team> teams = newList<Team>();

    privatevoid FillLists()

    {

        // Adding some countries.

        countries.Add(newCountry { Id = 1, Name = "England" });

        countries.Add(newCountry { Id = 2, Name = "Sweden" });

        countries.Add(newCountry { Id = 3, Name = "Spain" });

        // Adding some leagues with the Id of the country they belong to.

        leagues.Add(newLeague { Id = 1, Name = "Premier League", CountryId = 1 });

        leagues.Add(newLeague { Id = 2, Name = "Championship", CountryId = 1 });

        leagues.Add(newLeague { Id = 3, Name = "Superettan", CountryId = 2 });

        leagues.Add(newLeague { Id = 4, Name = "Allsvenskan", CountryId = 2 });

        // Adding some teams with the Id of the league they belong to.

        teams.Add(newTeam { Id = 1, Name = "Manchester United", LeagueId = 1 });

        teams.Add(newTeam { Id = 2, Name = "Arsenal", LeagueId = 1 });

        teams.Add(newTeam { Id = 3, Name = "Crystal Palace", LeagueId = 2 });

        teams.Add(newTeam { Id = 4, Name = "Watford", LeagueId = 2 });

        teams.Add(newTeam { Id = 5, Name = "Hammarby", LeagueId = 3 });

    }

 

    // *** INFO ***

    // The JavaScript code coming from the CascadingDropDown extender calls a web service method.

    // This method is expected to return an array of type CascadingDropDownNameValue[].

    // For the CascadingDropDownNameValue contructor the first argument is the list entry text. The second argument is the value

 

    [WebMethod]

    publicCascadingDropDownNameValue[] GetCountries(string knownCategoryValues, string category)

    {

        // Here we simply create a new list of CascadingDropDownNameValue.

        // We then fill the list will all countries from the list containing the countries and returns this as an array.

 

        List<CascadingDropDownNameValue> l = newList<CascadingDropDownNameValue>();

        var x = from c in countries select c;

        foreach (Country country in x)

        {

            l.Add(newCascadingDropDownNameValue(country.Name, country.Id.ToString()));

        }

        return l.ToArray();

    }

 

    [WebMethod]

    publicCascadingDropDownNameValue[] GetLeagues(string knownCategoryValues, string category)

    {

        // Here we create a new list of CascadingDropDownNameValue.

        // We then fill the list will all Leagues that has the provided countryId from the list containing the leagues.

 

        // First we need to determine the value selected in the first dropdown (countryId in this case).

        // There is helper method for this, ParseKnownCategoryValuesString.

        // We also need to validate this data. This is the "Category" in the web page.

        // One validated, we have the id in the countryId variable.

        int countryId;

        System.Collections.Specialized.StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

        if (!kv.ContainsKey("Country") || !Int32.TryParse(kv["Country"], out countryId))

        {

            thrownewArgumentException("Couldn't find Country.");

        };

 

        // We then fill the list will all leauges from the list containing the leagues where the countryId matches the incoming countryId.

        List<CascadingDropDownNameValue> l = newList<CascadingDropDownNameValue>();

        var x = from le in leagues where le.CountryId == countryId select le;

        foreach (League league in x)

        {

            l.Add(newCascadingDropDownNameValue(league.Name, league.Id.ToString()));

        }

        return l.ToArray();

    }

 

    [WebMethod]

    publicCascadingDropDownNameValue[] GetTeams(string knownCategoryValues, string category)

    {

        // This method does the same as the GetLeagues but takes the leagueId and select the teams based on that.

        int leagueId;

        System.Collections.Specialized.StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

        if (!kv.ContainsKey("League") || !Int32.TryParse(kv["League"], out leagueId))

        {

            thrownewArgumentException("Couldn't find League.");

        };

        List<CascadingDropDownNameValue> l = newList<CascadingDropDownNameValue>();

        var x = from t in teams where t.LeagueId == leagueId select t;

        foreach (Team team in x)

        {

            l.Add(newCascadingDropDownNameValue(team.Name, team.Id.ToString()));

        }

        return l.ToArray();

    }

 

    #region Classes

    // We have some countries.

    // Each country has some leagues and each league have some teams so the leagues

    // have an Id for the country it belongs to and the teams have an id for the league they belong to.

    publicclassCountry

    {

        publicint Id { get; set; }

        publicstring Name { get; set; }

    }

    publicclassLeague

    {

        publicint Id { get; set; }

        publicstring Name { get; set; }

        publicint CountryId { get; set; }

    }

    publicclassTeam

    {

        publicint Id { get; set; }

        publicstring Name { get; set; }

        publicint LeagueId { get; set; }

    }

    #endregion

}

 

. Now we have the web service that will deliver the data. So time to create the page that will hold the CascadingDropDown controls.

So add a new Web Form (Default.aspx) to the project.

. Full code for the web page:

 

<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"%>

 

<!DOCTYPEhtml>

 

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

    <title></title>

</head>

<body>

    <formid="form1"runat="server">

    <div>

   

        <%--We need the ScriptManager somewhere on the page (within the Form element)--%>

        <asp:ScriptManagerID="asm"runat="server"/>

          

        <%--Set up the DropDownlist that will be used. --%>

        <asp:DropDownListid="ddl_Countries"runat="server"/>

        <asp:DropDownListid="ddl_Leagues"runat="server"/>

        <asp:DropDownListid="ddl_Teams"runat="server"/>

 

        <ajaxToolkit:CascadingDropDown

            ID="ccdCountries"

            runat="server"

            ServicePath="FootballService.asmx"

            ServiceMethod="GetCountries"

            TargetControlID="ddl_Countries"

            Category="Country"/>

 

        <ajaxToolkit:CascadingDropDown

            ID="ccdLeagues"

            runat="server"

            ServicePath="FootballService.asmx"

            ServiceMethod="GetLeagues"

            TargetControlID="ddl_Leagues"

            ParentControlID="ddl_Countries"

            Category="League"

            EmptyText="No leagues for this country."/>

 

        <ajaxToolkit:CascadingDropDown

            ID="ccdTeams"

            runat="server"           

            ServicePath="FootballService.asmx"

            ServiceMethod="GetTeams"

            TargetControlID="ddl_Teams"

            ParentControlID="ddl_Leagues"

            Category="Team"

            EmptyText="No teams for this league."/>

 

<%--    Quick explanation.

        . The ServicePath points to the backing WebService.

        . The ServiceMethod points to the method in the backing WebService that will return the data.

        . The TargetControlID points to the dropdownlist to populate.

        . The ParentControlID points to the parent dropdownlist that controls the content of this list.

        . The Category is the information passed to the web method.

        . The EmptyText is shown when there is no data.

        . There are some more properties as well.--%>

 

    </div>

    </form>

</body>

</html>

 

Now you should be able to run the page and see how the dropdowns are populated based on the values of the parent control.

Hope this helps.

 

Filling a List Using CascadingDropDown(C#)

http://www.asp.net/web-forms/tutorials/ajax-control-toolkit/cascadingdropdown/filling-a-list-using-cascadingdropdown-cs