Create Cascading Dropdown List in ASP.NET MVC


In this example, you will learn how to create a Cascading Dropdown list in ASP.NET MVC.

What is cascading dropdown list?

Collection of dropdown list controls dependent on each other while each and every control depends on the parent control or the previous control. Each element in the dropdown list is controlled by the parent dropdown list and items are populated based on the item selected on the parent dropdown. For example, let’s implement Country and City dropdown lists. Depending on the country selected, the city dropdown list should change accordingly.

For this, we need to create two classes namely Country and City. In this example, we are not using a database. To populate from the database, we need to use Entity Framework which uses to map the object and the relational schema.

Now create the class Country.cs

Country.cs
public class Country
    {
        public int CountryID
        {
            get;
            set;
        }
        public string CountryName
        {
            get;
            set;
        }
    }

And the class City.cs

City.cs
public class City
    {
        public int CityID
        {
            get;
            set;
        }
        public string CityName
        {
            get;
            set;
        }
        public int CountryID {
            get;
            set;
        }
    }

After creating the respective classes, next, we have to create our controller class. In this example, we are using a controller to populate the dropdown lists. if you are planning to use a particular database to populate dropdowns, all the queries should be placed here. Further, we need to add some methods to retrieve data from the populated drop-down lists. For that, we use ActionResult return type methods in the controller class. Typically action methods return streams of files, views and even redirect to the particular controller we are specifying. Now let’s implement the controller.

public class CascadingDropDownController : Controller
    {
        List<Country> countryList = new List<Country>()
        {
            new Country() { CountryID = 1, CountryName = "USA" },
            new Country() { CountryID = 2, CountryName = "UK" },
           
        };


        List<City> cityList = new List<City>()
        {
            new City() { CityID = 1, CityName = "New York", CountryID = 1 },
            new City() { CityID = 2, CityName = "Washington", CountryID = 1 },
            new City() { CityID = 3, CityName = "Chicago", CountryID = 1 },
            new City() { CityID = 4, CityName = "London", CountryID = 2 },
            new City() { CityID = 5, CityName = "Leeds", CountryID = 2 },
          
        };

        public ActionResult GetCountryies()
        {
            return Json(countryList, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetCities(int cID)
        {
            var cities = cityList.Where(p => p.CountryID == cID);
            return Json(cities, JsonRequestBehavior.AllowGet);
        }
      
    }

In here, each and every city is related to the Country ID provided and based on the Country ID, all the cities are retrieved. When we pass the Country ID to the GetCities() method, it searches for the cities with the city list and returns the results as JSON. To assign the values to the cities variable, we use arrow function (=>) which is available with the new versions of ASP.NET. But if you are using a lower version, this might not work.

Why JsonRequestBehavior.AllowGet is important?

By default MVC architecture denies HTTP GET methods to protect the user from the attacks related to the JSON format. In ASP.NET, if you need to implement the get method, we should explicitly use the JsonRequestBehavior.AllowGet property in the method.
So far we have completed the backend part of our cascading dropdown list application and now we need to create the view page to show the 2 dropdown lists we created.

So far we have completed the backend part of our cascading dropdown list application and now we need to create the view page to show the 2 dropdown lists we created.

<div>
    <label for="country">Country</label>
    <select id="country"></select>
    <label for="city">City</label>
    <select id="city"></select>
</div>

Next, add the code to get the list of countries and cities upon the selection of the dropdown list. For that, we use JQuery plugin and you need to import it to the file using the below code.

<script src="~/Scripts/jquery-1.10.2.min.js"></script>

Afterward, we need to set the cities according to the selection of the country. For that, we take the country ID of the selected country from the dropdown list and passes onto the cities method. From that method, cities which match with the country id is populated into the cities dropdown list.

$(document).ready(function () {

   // Get a list of countries and a list of cities
   $.getJSON('/countries', null, function (data) {
     $.each(data, function () {
       $('#country').append('<option value=' + this.CountryID + '>' + this.CountryName + '</option>');
       });
   $.getJSON('/cities', { cID: $('#country').val() }, function (data) {
     $.each(data, function () {
       $('#city').append('<option value=' + this.CityID + '>' + this.CityName + '</option>');
       });
    }).fail(function() {
         alert('Cannot retrieve cities!');
    });
  }).fail(function()  {
        alert('Cannot retrieve countries!');
     });
});

Finally, we need to handle the change event of the countries dropdown list. On the change event, we should trigger the population methods we implemented earlier. JQuery provides a function to handle these change events using change() method.

 // Change event of countries dropdown list
    $('#country').change(function () {
        $('#city option').remove();
        $.getJSON('/getcities', { cID: $('#country').val() }, function (data) {
            $.each(data, function () {
                $('#city').append('<option value=' + 
                  this.CityID + '>' + this.CityName + '</option>');
            });
        }).fail(function () {
            alert('Cannot retrieve cities!');
        });
    });

Output

                     

 

Related Articles

Exception Handling in C#

An Overview of Object-Oriented Programming in C#

Introduction to Micro-services

Tutorials Panel

About Tutorials Panel

programming tutorial and source code for Software Engineers and developers. https://twitter.com/TutorialsPanel

View all posts by Tutorials Panel →

Leave a Reply