Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

An ASP.NET MVC Cascading Dropdown List

0.00/5 (No votes)
6 Mar 2015 1  
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.

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:

        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.

<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.

@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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here