C# Ajax Control Toolkit CascadingDropDown Step By Step

Posted by OmegaMan at February 24, 2009

Category: Ajax, ASP.Net

Tags: ,

This breaks down step by step what to do to create a cascading drop down using the Ajax Control toolkit in C# and Asp.net 3.5.

  1. Create a web service outside the html page. Decorate the class with the below attribute
  2. // To allow this Web Service to be called from script,
    // using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]
    public class AjaxServices : System.Web.Services.WebService
    { ... }
  3. Now create a webmethod with any name. Note if the webmethod resides on the same page (a page level service method) as your html page, make it a static method. But normally if you are creating an asmx web page, do not make it static.  This example is not creating a page level service method. The return is a CascadingDropDownNameValue [] type which is found in the ajax toolkit. The parameters of the webservice method has to be as

    string knownCategoryValues
    string category.

    Those parameters have to be in that case and format; do anything else and a general ajax failure will occur when ajax calls the method. The below shows a Linq db call returning the proper object, and handling the category and the value which will be sent. See the notes in the code about what ajax actually sends. .

  4. [WebMethod]
    public CascadingDropDownNameValue[] GetExportTypes   ( string knownCategoryValues, string category )
    {
    
    GTCDataContext gtdc       = new GTCDataContext( Utilities.GetConnectionString() );
    IEnumerable<CascadingDropDownNameValue> vals = null;
    int targetID = 0;
    
    // The data comes in as "XXXX:1" where XXXX is the originating
    // control category, which is *not* the same as the category.
    // The 1st control will pass in nothing (empty) for the
    // knownCategory while 2+ control will pass in
    // the originating category and its ID with a :.// Remove the XXXX: and extract an integer value.
    if (string.IsNullOrEmpty( knownCategoryValues ) == false)
        int.TryParse(
            Regex.Match( knownCategoryValues,
                         @"(\d+)",
                         RegexOptions.Compiled).Groups[0].Value,
                         out targetID);
    
    switch ( category )
    {
        case "Type" : // 1st Initiating DropDownList
            vals = from tp in gtdc.Type_Exports
                   select new CascadingDropDownNameValue
                   {
                       name = tp.Text,
                       value = tp.Export_Type_ID.ToString(),
                   };
            break;
    
        case "SubType": // Next/child DropDownList
            vals = from tp in gtdc.Type_Export_SubTypes
                   where tp.ID_Type_Export == targetID
                   select new CascadingDropDownNameValue
                   {
                       name = tp.Text,
                       value = "0",
                   };
    
            break;
    }
    
    return vals.ToArray<CascadingDropDownNameValue>();
    
    }
  5. Test your webservice before trying to hook it up! Very important.
  6. Add an ajax ScriptManager  to the target html page.
  7. Add an ajax UpdatePanel to the page.
  8. Within the panel add the DropDownLists, two in this example.
  9. Add a CascadingDropDown control extender to the page for each dropdownlist which will be used. Set the TargetControlID to the id of desired dropdown to work with.
  10. <asp:DropDownList ID="DropDownList1" runat="server" />
    <cc1:CascadingDropDown ID="CascadingDropDown1"
                           runat="server"
                           Category="Type"
                           TargetControlID="DropDownList1"
                           LoadingText="Acquiring ..."
                           PromptText="Select Type Of Export"
                           ServiceMethod="GetExportTypes"
                           ServicePath="~/AjaxServices.asmx"
    
                           >
    </cc1:CascadingDropDown>
    
    <asp:DropDownList ID="DropDownList2"
                      runat="server"
                      AutoPostBack="false">
    </asp:DropDownList>
    <cc1:CascadingDropDown ID="CascadingDropDown2"
                           runat="server"
                           Category="SubType"
                           TargetControlID="DropDownList2"
                           ParentControlID="DropDownList1"
                           LoadingText="Acquiring ..."
                           PromptText="Select End Use"
                           ServiceMethod="GetExportTypes"
                           ServicePath="~/AjaxServices.asmx"
    
                           >
    </cc1:CascadingDropDown>
  11. If your last drop down is doing a postback on the page tag turn off event validation or a postback javascript error will be thrown. (The above example has AutoPostBack turned off so no need to do step 7). EnableEventValidation=”false”
  12.  
     
     
Share

14 Comments

  1. V@CN says

    I think the key step is how to build a CascadingDropDown

    Reply
  2. Brian says

    I spent two hours trying to figure out why I was getting a 500 error when everywhere else said I had everything set up right. The problem ended up being:
    GetSchools(string KnownCategoryValues, string Category)
    I can’t believe it was a stupid case problem.

    Thanks for the help,
    Brian

    Reply
  3. omegaman says

    *Everyone* spends the same amount of time with the case situation! Glad to help.

    Reply
  4. Scott Vickery says

    Thanks for the quick start. It came in real handy.

    Question for you: This works great when adding a new row to a table. But, when editing a row that exists, and, there are already values for what will be in the cascading dropdown, how can I set the values in the code behind before I get to the page? The problem is that I am building an edit form dynamically, and, the drop down datasource is not set until the page is loaded.

    Does this make sense?

    Thanks,
    Scott

    Reply
  5. omegaman says

    You need some triggering event which will refresh the dropdown appropriately. I used Linq in the back end and would dynamically bind the data after such change. I had multiple drop downs, one selection from a top one would trigger changes in child drop downs. Play around with it in a test project to get the feel of the CDD. Sorry I couldn’t be more help. Try posting the issue in the asp.net forums. HTH

    Reply
  6. Scott Vickery says

    Answered my own question. Set the SelectedValue of the CascadingDropDown control.

    Thanks again,
    Scott

    Reply
  7. Mohammed says

    hi all
    i have problem with CascadingDropDown control and the problem is when i choose items and click link , postback has been done ,so the child CascadingDropDown lost its value

    anyone can help me to solve this problem

    Reply
  8. Alan Feekery says

    The value “knownCategoryValues” is wrong.

    It is a string that contains “X:Y;”

    X “IS” the category specified in the cascading drop down control. In other words X == category.

    Y is the selected value of the parent control.

    Reply
  9. Chen says

    Hi,

    I am trying to disable the parent, but keep its select value. Te child is still alive .. Thanks

    Reply
  10. Tony Dunsworth says

    Well well well, after I don’t know how long today, this little tutorial helped me figure out just the small things I was getting wrong…..

    Thanks a million for that.

    Reply
  11. Dheeraj says

    Thanks for the step by step description. I just want to ask How to do the same using WCF ?
    Thanks in Advance.

    Reply
  12. Nathan says

    Thanks for this tutorial. Been scratching my head over what I’ve been doing wrong. Got my answer in your first paragraph – “static method”. Seems obvious now. Thanks.

    Reply
  13. Rich says

    Is it possible to use a WCF service instead of asmx? I created a wcf service, it gets called correctly but the values come back as undefined in the target control.

    Reply
  14. Chanchal singh says

    I want To bind gridview for last dropdown selectedindexchange but not possible in CascadingDropDown some help to execute postback and bind gridview at last dropdown postback

    Reply

Leave a comment

(required)
(required) (will not be published)

This site uses Akismet to reduce spam. Learn how your comment data is processed.