Header Ads

How to Implement Cascading Dropdowns in ASP.NET MVC

Dropdown menu is one of the key User Interface (UI) component on any website when dealing with user selection from a list. A website might have one to multiple independent dropdown menus depending on the business requirements. However, for more sophisticated business requirements, there may be a need to have multiple dropdown menus, whose user selected data population depends on one another. This type of dropdown menus are bound with each other, representing data on one of the dropdown menu depends on the selection of another dropdown menu. The combination of ASP.NET MVC platform with Bootstrap style UI framework provides a rich interactive multiple dropdown menus binding UI component.

Today, I shall be demonstrating binding of multiple dropdown menus using ASP.NET MVC web platform and bootstrap style UI framework.



Prerequisites:

Before proceeding any further in this article, following are some of the many prerequisites for this tutorial:
  1. Knowledge of ASP.NET MVC.
  2. Knowledge of HTML.
  3. Knowledge of JavaScript.
  4. Knowledge of Bootstrap.
  5. Knowledge of JQuery.
  6. Knowledge of C# Programming.
The running working source code solution for this tutorial is being developed in Microsoft Visual Studio 2022 Professional. For the source code click on the download button below.

Download Now!

Let's begin now.

1) In the first step, create a new ASP.NET MVC (.NET framework) web project and name it "MVCDropDownMultiBind".

2) Create suitable default layout for your project and include relevant JavaScripts and CSS styles libraries references. I am using Bootstrap-Select plugin for bootstrap 3.4.1 framework. Download this plugin for much rich interactive dropdown menu experience. 

3) The data structure of a dropdown menu is value-text type list, where value can be associated with unique identification key (ID) and the text will be the end-user friendly display text. When user selects an item from the dropdown menu, the system will capture the related ID key of that item. For this type of scheme, create a ViewModel for both dropdown menus with ID selection as property. As shown in below lines of code i.e.

...

        /// <summary>
        /// Select country ID property
        /// </summary>
        [Display(Name = "Choose country")]
        public int? SelectedCountryId { get; set; }

        /// <summary>
        /// Select state ID property
        /// </summary>
        [Display(Name = "Choose state")]
        public int? SelectedStateId { get; set; }

...
 
4) In your target code file, load dropdown menu lists into ViewBag data properties. My code file is Controllers/HomeController.cs.
 
5) I am using country list and state list as multiple dropdown menu data bindings. By default, country dropdown menu will contain list of countries and state list will be emptied. When end-user selects any country from the dropdown menu then related state list will be populated within the state dropdown menu. Therefore, to create a bootstrap-select plugin style dropdown menu, incorporate below lines of code into your target page. I have incorporated below lines of code inside the Views/Home/index.cshtml page file i.e.
 
...

        <div class="row">
            <div class="col-xs-4 col-xs-push-2">
                <div class="form-group">
                    @Html.DropDownListFor(m => m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new { id = "CountryList", @class = "selectCountry show-tick form-control" })
                </div>
            </div>

            <div class="col-xs-4 col-xs-push-2">
                <div class="form-group">
                    @Html.DropDownListFor(m => m.SelectedStateId, this.ViewBag.StateList as SelectList, new { id = "StateList", @class = "selectState show-tick form-control" })
                </div>
            </div>
        </div>

...

6) Now to bind the dropdown menus together, the methodology that we are proposing here is adding a change event which needs to be attached to the country dropdown menu. This means that when end-user selection happens or changes that change is captured and base on that selection, the related state list data will be populated within the state dropdown menu. To configure initial setup of the dropdown menus according to bootstrap-select plugin, you can look into our article ASP.NET MVC5: Bootstrap Style Dropdown Plugin to setup a simple bootstrap-select plugin style dropdown menu. Now, create a JavaScript custom script file into your project, name it Scripts/script-bootstrap-select.js and add below lines of code to create the binding change event for country dropdown menu   i.e.
 
...

    $('.selectCountry').on('change',
        function ()
        {
            // Initialization
            var countryId = $('option:selected', $(this)).val();

            // Loading States List.
            $.ajax({
                url: '/Home/GetStates',
                type: "GET",
                dataType: "JSON",
                data: { countryId: countryId },
                success: function (result)
                {
                    $('#StateList').html(""); // clear before appending new list
                    var items = '';

                    $.each(result, function (i, data)
                    {
                        $('#StateList').append($('<option></option>').val(data.Value).html(data.Text));
                    });

                    // Refresh.
                    $('#StateList').selectpicker('refresh');
                }
            });
        });
...
 
In the above code, I am first capturing the country ID from the end-user selection then making an AJAX method call to my back-end server in order to get my related states list and then finally, populate my states dropdown menu accordingly.

7) Now, when you execute your project, you will be able to see multiple dropdown menus bind with each other in action as shown below i.e. 






Conclusion

In this article, you will learn to bind multiple dropdown menus using ASP.NET MVC platform and Bootstrap UI framework. You will also learn about the methodology that we have proposed to bind two interdependent dropdown menus together by using the JQuery change event. Finally, you will be able to incorporate binding dropdown menus into your own project.

Video Demo


4 comments:

  1. Use Subscribe button at page end to follow us.

    ReplyDelete
  2. fantastic post, very informative. I ponder why the opposite experts of this secgor do not realize this. You must continue your writing. I’m sure, you have a great readers’ base already northlandblog.

    ReplyDelete
  3. The article on UAEScrap is an eye-opener for anyone interested in the recycling industry, especially in a place like the UAE where sustainability is becoming more important. It’s fascinating to see how the scrap business is not just about discarding old materials but actually turning them into valuable resources. The detailed breakdown of how different types of scrap are processed gives a real appreciation for the complexities involved. I love how the article also touches on the economic and environmental benefits, showing that this industry is crucial for a greener future. It's clear that the scrap industry is a vital part of the circular economy in the UAE. Great read for anyone curious about how sustainability and business can go hand in hand!

    ReplyDelete