Click here to Skip to main content
13,792,845 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

72.4K views
19 bookmarked
Posted 6 Mar 2015
Licenced CPOL

An ASP.NET MVC Cascading Dropdown List

, 6 Mar 2015
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

George MVC Study
Software Developer
Canada Canada
I am working with ASP.NET related technologies.

You may also be interested in...

Comments and Discussions

 
QuestionExcellent Pin
Francisco A F. A.29-Oct-17 19:18
memberFrancisco A F. A.29-Oct-17 19:18 
GeneralMessage Closed Pin
4-May-16 2:08
membervijay saklani4-May-16 2:08 
QuestionA great example! Pin
Hannelore26-Dec-15 8:21
memberHannelore26-Dec-15 8:21 
QuestionNot a complete article Pin
martin@martinleir.com6-Nov-15 8:30
membermartin@martinleir.com6-Nov-15 8:30 
QuestionIt's not quite as simple as this though Pin
Bill Ahern30-Oct-15 12:29
memberBill Ahern30-Oct-15 12:29 
PraiseRe: It's not quite as simple as this though Pin
Member 121080792-Nov-15 13:24
memberMember 121080792-Nov-15 13:24 
QuestionCascading dropdown Pin
Uwakpeter3-Oct-15 12:00
professionalUwakpeter3-Oct-15 12:00 
QuestionCan i use this with my database? Pin
Member 1161809729-Sep-15 5:58
memberMember 1161809729-Sep-15 5:58 
SuggestionThe solution was good but why not try the SharePoint Cascading dropdown Pin
Junell Zenarosa27-Apr-15 20:59
professionalJunell Zenarosa27-Apr-15 20:59 
QuestionGood, but suggest alternative Pin
Matt Slay9-Mar-15 8:03
memberMatt Slay9-Mar-15 8:03 
GeneralRe: Good, but suggest alternative Pin
George MVC Study9-Mar-15 8:47
memberGeorge MVC Study9-Mar-15 8:47 
AnswerRe: Good, but suggest alternative Pin
Mr. Javaman9-Mar-15 13:36
memberMr. Javaman9-Mar-15 13:36 
GeneralRe: Good, but suggest alternative Pin
Matt Slay9-Mar-15 15:17
memberMatt Slay9-Mar-15 15:17 
GeneralRe: Good, but suggest alternative Pin
George MVC Study10-Mar-15 4:24
memberGeorge MVC Study10-Mar-15 4:24 
QuestionVery Nice Demo of using Json for post back... Pin
Mr. Javaman8-Mar-15 18:36
memberMr. Javaman8-Mar-15 18:36 
GeneralRe: Very Nice Demo of using Json for post back... Pin
George MVC Study9-Mar-15 8:47
memberGeorge MVC Study9-Mar-15 8: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.181207.3 | Last Updated 6 Mar 2015
Article Copyright 2015 by George MVC Study
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid