Casecading Dropdown List in Core MVC

Problem Defination :- In the below image there are three dropdownlist i.e one for Country second for State and third for City. Our requirement to filter the States based on the selected Country from Country Dropdown and filter the Cities based on State dropdown selection.

Image is not available

Implementation :- To implement dropdownlist firstly we have to follow below steps

  • Create a Model Class for Country.
  • Create a Model Class for State.
  • Create a Model Class for City.
  • Create a Controller named it Casecade.
  • Create a Action Method named it Casecade inside the controller.
  • Create three differnet methods for GetCountry Data from database , Get State data based on country from database and create a method for get City data based on state from database.
  • Create a JavaScript file named it as Casecade.js for javascript code.
  • Add these three model classes into the DbContext class and then execute the migration commands.

In The implemetation phase we will create three model classes which is used for dropdownlist. Below is the code for Country Model Country Model class.

Image is not available

                
    public class Country
    {
        [Key]
        public int countryId { get; set; }
        public string countryName { get; set; }
    }
                            
                        

Below is the model class for State,has three properties StateId,StateName and Country in which the State belongs.

Image is not available

                
    public class State
    {
        [Key]
        public int stateId { get; set; }
        public string stateName { get; set; }
        public Country country { get; set; }
    }
                            
                        

Below is the model class for City,has three properties CityId,CityName and State in which the City belongs.

Image is not available

                
    public class City
    {
        [Key]
        public int cityId { get; set; }
        public string cityName { get; set; }
        public State state { get; set; }
    }
                            
                        

Now create a DBContext class and named it as demoDBcontext and add the below three DBSet into this class that will generate the table into the database when you run the migration commands.


                
        public DbSet Countries { get; set; }
        public DbSet States { get; set; }
        public DbSet Cities { get; set; }
                             
                        

Now Create the Controller with named Casecade and write the below Action Methods into it. GetCountry() is the method in which we are fetching the list of countries from database and return it into the JSONResult.This GetCountry() is further used in Javascript file to fill the Country Dropdownlist.
GetState(int countryId) is the method in which we are fetching the list of states from database based on the countryId selected from the Country Dropdownlist and return it into the JSONResult.This GetState(int countryId) is further used in Javascript file to fill the State Dropdownlist.
GetCities(int stateId) is the method in which we are fetching the list of cities from database based on the stateId selected from the State Dropdownlist and return it into the JSONResult.This GetCities(int stateId) is further used in Javascript file to fill the City Dropdownlist.

                
 public IActionResult Cascade()
        {
            return View();
        }
        public JsonResult GetCountry()
        {
            var contryList = _db.Countries.ToList();
            return new JsonResult(contryList);
        }
        public JsonResult GetState(int countryId)
        {
            var stateList = _db.States.Where(p=>p.country.countryId==countryId).ToList();
            return new JsonResult(stateList);
        }
        public JsonResult GetCities(int stateId)
        {
            var cityList = _db.Cities.Where(p => p.state.stateId == stateId).ToList();
            return new JsonResult(cityList);
        }
                                         
                        

Now create a View for the Casecade Action Method and write the below code.

Image is not available

Now create a Javascript file and named as it casecade.js and write the below code.
GetCountryList() is the function in which we are fetching the Countries from calling the url: '/Cascade/GetCountry' and it returns the list of Countries that further append into the Country Dropdownlist.$('#country').change(function () is used on change the selected index of country dropdownlist and it fills the States dropdownlist same thing done with State change also.

                
    $(document).ready(function () {
    GetCountryList();
    $('#state').attr('disabled', true);
    $('#city').attr('disabled', true);
    $('#country').change(function () {
        $('#state').attr('disabled', false);
        var cid = $(this).val();
        $('#state').empty();
        $('#state').append('');
        $.ajax({
            url: '/Cascade/GetState?countryId='+cid,
            success: function (result) {
                $.each(result, function (i, data) {
                    $('#state').append('');
                });
            }
        });
    });
    $('#state').change(function () {
        $('#city').attr('disabled', false);
        var sid = $(this).val();
        $('#city').empty();
        $('#city').append('');
        $.ajax({
            url: '/Cascade/GetCities?stateId=' + sid,
            success: function (result) {
                $.each(result, function (i, data) {
                    $('#city').append('');
                });
            }
        });
    });
});
function GetCountryList() {
    $.ajax({
        url: '/Cascade/GetCountry',
        success: function (result) {
            $.each(result, function (i, data) {
                $('#country').append('');
            });
        }
    });
}
                            
                        

Now run the application it will work and you will be able to filter the States based on the Country and filter the Cities based on the States.


Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.