Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Javascript
Tip/Trick

An ASP.NET MVC Cascading Dropdown List

Rate me:
Please Sign up or sign in to vote.
4.28/5 (17 votes)
6 Mar 2015CPOL 108.6K   18   16
This tip shows an example of ASP.NET MVC cascading dropdown list.

Introduction

The code in this tip shows an example of an ASP.NET MVC cascading dropdown list. In this example, there are two dropdown lists. When the first dropdown list selection is changed, the options in the second dropdown list are changed by a call to an MVC controller.

Background

In ASP.NET web forms, there is a server control called CascadingDropDown in ASP.NET AJAX Control Toolkit. However, ASP.NET MVC doesn't have any server control. Similar functions have to be implemented by other ways such as using jQuery Plugins or custom codes. For a cascading dropdown, it may be easier to just code by hand. The method helps in learning and is also very flexible.

Using the Code

First, create two user classes for the dropdown list data.

C#
public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int CategoryID { get; set; }
}

Second, create a MVC controller and add the following objects and functions:

C#
        List<Category> lstCat = new List<Category>()
        {
            new Category() { CategoryID = 1, CategoryName = "Dairy" },
            new Category() { CategoryID = 2, CategoryName = "Meat" },
            new Category() { CategoryID = 3, CategoryName = "Vegetable" }
        };

        List<Product> lstProd = new List<Product>()
        {
            new Product() { ProductID = 1, ProductName = "Cheese", CategoryID = 1 },
            new Product() { ProductID = 2, ProductName = "Milk", CategoryID = 1 },
            new Product() { ProductID = 3, ProductName = "Yogurt", CategoryID = 1 },
            new Product() { ProductID = 4, ProductName = "Beef", CategoryID = 2 },
            new Product() { ProductID = 5, ProductName = "Lamb", CategoryID = 2 },
            new Product() { ProductID = 6, ProductName = "Pork", CategoryID = 2 },
            new Product() { ProductID = 7, ProductName = "Broccoli", CategoryID = 3 },
            new Product() { ProductID = 8, ProductName = "Cabbage", CategoryID = 3 },
            new Product() { ProductID = 9, ProductName = "Pepper", CategoryID = 3 }
        };

        public ActionResult GetCategories()
        {
            return Json(lstCat, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetProducts(int intCatID)
        {
            var products = lstProd.Where(p => p.CategoryID == intCatID);
            return Json(products, JsonRequestBehavior.AllowGet);
        }

Third, create a view page and add the following markups.

HTML
<div>
    <label for="category">Category</label>
    <select id="category">
    </select>
    <label for="product">Product</label>
    <select id="product">
    </select>
</div>

Last, add the following jQuery code on the view page. Don't forget to reference jQuery librar in the layout view page.

JavaScript
@section scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            // Get a list of categories and a list of products of the first category.
            $.getJSON('/home/GetCategories', null, function (data) {
                $.each(data, function () {
                    $('#category').append('<option value=' + 
                      this.CategoryID + '>' + this.CategoryName + '</option>');
                });
                $.getJSON('/home/GetProducts', { intCatID: $('#category').val() }, function (data) {
                    $.each(data, function () {
                        $('#product').append('<option value=' + 
                          this.ProductID + '>' + this.ProductName + '</option>');
                    });
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    alert('Error getting products!');
                });
            }).fail(function (jqXHR, textStatus, errorThrown) {
                alert('Error getting categories!');
            });

            // Dropdown list change event.
            $('#category').change(function () {
                $('#product option').remove();
                $.getJSON('/home/GetProducts', { intCatID: $('#category').val() }, function (data) {
                    $.each(data, function () {
                        $('#product').append('<option value=' + 
                          this.ProductID + '>' + this.ProductName + '</option>');
                    });
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    alert('Error getting products!');
                });
            });
        });
    </script>
}

That is it. The cascading dropdown lists are created.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Canada Canada
I am working with ASP.NET related technologies.

Comments and Discussions

 
QuestionExcellent Pin
Francisco A F. A.29-Oct-17 18:18
Francisco A F. A.29-Oct-17 18:18 
QuestionA great example! Pin
Hannelore26-Dec-15 7:21
Hannelore26-Dec-15 7:21 
QuestionNot a complete article Pin
martin@martinleir.com6-Nov-15 7:30
martin@martinleir.com6-Nov-15 7:30 
QuestionIt's not quite as simple as this though Pin
Bill Ahern30-Oct-15 11:29
Bill Ahern30-Oct-15 11:29 
PraiseRe: It's not quite as simple as this though Pin
Member 121080792-Nov-15 12:24
Member 121080792-Nov-15 12:24 
QuestionCascading dropdown Pin
Uwakpeter3-Oct-15 11:00
professionalUwakpeter3-Oct-15 11:00 
QuestionCan i use this with my database? Pin
Member 1161809729-Sep-15 4:58
Member 1161809729-Sep-15 4:58 
SuggestionThe solution was good but why not try the SharePoint Cascading dropdown Pin
Junell Zenarosa27-Apr-15 19:59
professionalJunell Zenarosa27-Apr-15 19:59 
QuestionGood, but suggest alternative Pin
Matt Slay9-Mar-15 7:03
Matt Slay9-Mar-15 7:03 
This is good example, but I also want to suggest KnockoutJS which will do automatic binding of select list options to a Json veiwmodel using the same MVC controller actions you built on the back end.
GeneralRe: Good, but suggest alternative Pin
George MVC Study9-Mar-15 7:47
George MVC Study9-Mar-15 7:47 
AnswerRe: Good, but suggest alternative Pin
Your Display Name Here9-Mar-15 12:36
Your Display Name Here9-Mar-15 12:36 
GeneralRe: Good, but suggest alternative Pin
Matt Slay9-Mar-15 14:17
Matt Slay9-Mar-15 14:17 
GeneralRe: Good, but suggest alternative Pin
George MVC Study10-Mar-15 3:24
George MVC Study10-Mar-15 3:24 
QuestionVery Nice Demo of using Json for post back... Pin
Your Display Name Here8-Mar-15 17:36
Your Display Name Here8-Mar-15 17:36 
GeneralRe: Very Nice Demo of using Json for post back... Pin
George MVC Study9-Mar-15 7:47
George MVC Study9-Mar-15 7:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.