Cascading Dropdown List in ASP.NET Core MVC

How to Implement Cascading Dropdown List in ASP.NET Core MVC

In this article, I will explain How to Implement a Cascading Dropdown List in ASP.NET Core MVC using jQuery Ajax with an Example. Please read our previous article discussing How to Perform CRUD Operation on a Single Page in ASP.NET Core MVC using jQuery Ajax.

What is a Cascading Down List?

A Cascading Drop-down List is a user interface element used in web forms and applications. It consists of two or more drop-down lists where the options in one list depend on the selection made in another. When a user makes a selection in the first drop-down, it dynamically updates the choices available in the subsequent drop-down(s) based on that selection. This interdependence creates a “cascade” effect.

For example, in a form asking for a user’s location, the first drop-down might list countries. Once the user selects a country, the second drop-down will populate with states or provinces within that country. If applicable, a third drop-down might then offer city choices based on the state or province selected.

Cascading drop-down lists are commonly used to simplify the form filling process by guiding the user through a logically ordered sequence of choices, reducing the likelihood of errors and improving user experience.

Cascading Dropdown List in ASP.NET Core MVC using jQuery AJAX

Using jQuery AJAX, let us create a cascading dropdown list for Country, State, and City in ASP.NET Core MVC. Creating a cascading dropdown list in ASP.NET Core MVC using jQuery AJAX involves several steps. The basic idea is to have dropdown lists where the selection in one dropdown dynamically sets the options of the next dropdown.

Set Up the ASP.NET Core MVC Project

First, create a new ASP.NET Core MVC project named CascadingDemo and add the required packages. As we are going to interact with the SQL Server database using the Entity Framework Core Code First Approach, please add the following packages from the NuGet Package Manager:

  • EF Core DB Provider: Microsoft.EntityFrameworkCore.SqlServer
  • EF Core Tools: Microsoft.EntityFrameworkCore.Tools
Create the Models

Next, create the models for Country, State, and City as follows:

Country Model:

Create a class file named Country.cs within the Models folder and then copy and paste the following code:

namespace CascadingDemo.Models
{
    public class Country
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }
        // Other properties
    }
}
State Model:

Create a class file named State.cs within the Models folder and then copy and paste the following code:

namespace CascadingDemo.Models
{
    public class State
    {
        public int StateId { get; set; }
        public string StateName { get; set; }
        public int CountryId { get; set; }
        // Other properties
    }
}
City Model:

Create a class file named City.cs within the Models folder and then copy and paste the following code:

namespace CascadingDemo.Models
{
    public class City
    {
        public int CityId { get; set; }
        public string CityName { get; set; }
        public int StateId { get; set; }
        // Other properties
    }
}
Creating DbContext Class:

We are going to perform the database CRUD operation using Entity Framework Core Code First Approach. So, create the following EFCodeDBContext class within the Models folder and please change the database connection string details.

using Microsoft.EntityFrameworkCore;
namespace CascadingDemo.Models
{
    public class EFCodeDBContext : DbContext
    {
        //Constructor calling the Base DbContext Class Constructor
        public EFCodeDBContext() : base()
        {
        }

        //OnConfiguring() method is used to select and configure the data source
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Configuring the Connection String
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EFCoreDemoDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        //Adding Domain Classes as DbSet Properties
        public DbSet<Country> Countries { get; set; }
        public DbSet<State> States { get; set; }
        public DbSet<City> Cities { get; set; }
    }
}
Generate the Migration and Update the Database:

Open Package Manager Console and Execute the following add-migration and update-database commands. You can give any name to your migration. Here, I am giving Mig1. The name that you are giving it should not be given earlier.

How to Implement a Cascading Dropdown List in ASP.NET Core MVC using jQuery Ajax with an Example

This should generate the EFCoreDemoDB with the Countries, States, and Cities database table in the SQL Server database as shown in the below image:

How to Implement a Cascading Dropdown List in ASP.NET Core MVC using jQuery Ajax with an Example

Please execute the following SQL script to populate the above three database tables with some dummy data:

-- Insert India into Countries Table
INSERT INTO Countries (CountryName) VALUES ('India');
DECLARE @IndiaId INT = SCOPE_IDENTITY();

-- Insert States into States Table
INSERT INTO States (StateName, CountryId) VALUES 
('Delhi', @IndiaId),
('Odisha', @IndiaId),
('Bihar', @IndiaId);

DECLARE @DelhiId INT, @OdishaId INT, @BiharId INT;
SELECT @DelhiId = SCOPE_IDENTITY() - 2, @OdishaId = SCOPE_IDENTITY() - 1, @BiharId = SCOPE_IDENTITY();

-- Insert Cities into Cities Table
-- For Delhi
INSERT INTO Cities (CityName, StateId) VALUES 
('New Delhi', @DelhiId),
('Delhi', @DelhiId);

-- For Odisha
INSERT INTO Cities (CityName, StateId) VALUES 
('Bhubaneswar', @OdishaId),
('Cuttack', @OdishaId),
('Rourkela', @OdishaId);

-- For Bihar
INSERT INTO Cities (CityName, StateId) VALUES 
('Patna', @BiharId),
('Gaya', @BiharId),
('Bhagalpur', @BiharId);
Configuring the DbContext Service:

As we are using the EFCodeDBContext service in our controller. So, to inject the EFCodeDBContext instance by the MVC Framework, we need to register the EFCodeDBContext service to the built-in dependency injection container. So, add the following statement to the program.cs class file:

builder.Services.AddDbContext<EFCodeDBContext>();

Create the Controller Actions

We need three actions in our controller: one for each dropdown list. So, modify the Home Controller as follows:

using CascadingDemo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace CascadingDemo.Controllers
{
    public class HomeController : Controller
    {
        private readonly EFCodeDBContext _context;

        public HomeController(EFCodeDBContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            var countries = _context.Countries.ToList();
            return View(countries);
        }

        [HttpGet]
        public IActionResult GetCountries()
        {
            var countries = _context.Countries.ToList();
            return Json(new SelectList(countries, "CountryId", "CountryName"));
        }

        [HttpGet]
        public IActionResult GetStates(int countryId)
        {
            var states = _context.States.Where(x => x.CountryId == countryId).ToList();
            return Json(new SelectList(states, "StateId", "StateName"));
        }

        [HttpGet]
        public IActionResult GetCities(int stateId)
        {
            var cities = _context.Cities.Where(x => x.StateId == stateId).ToList();
            return Json(new SelectList(cities, "CityId", "CityName"));
        }
    }
}
Create the View

In your view, you’ll have three dropdown lists. Initially, only the Countries dropdown will be populated. So, modify the Index view of the Home Controller as follows:

@model List<Country>
@{
    ViewData["Title"] = "Home Page";
}

<select id="Countries" name="CountryId">
    <option value="">Select Country</option>
    @foreach (var country in Model)
    {
        <option value="@country.CountryId">@country.CountryName</option>
    }
</select>

<select id="States" name="StateId">
    <option value="">Select State</option>
</select>

<select id="Cities" name="CityId">
    <option value="">Select City</option>
</select>


<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        $('#Countries').change(function () {
            var countryId = $(this).val();
            $.getJSON('@Url.Action("GetStates")', { countryId: countryId }, function (states) {
                var statesSelect = $('#States');
                statesSelect.empty();
                $.each(states, function (index, state) {
                    statesSelect.append($('<option/>', {
                        value: state.value,
                        text: state.text
                    }));
                });
            });
        });

        $('#States').change(function () {
            var stateId = $(this).val();
            $.getJSON('@Url.Action("GetCities")', { stateId: stateId }, function (cities) {
                var citiesSelect = $('#Cities');
                citiesSelect.empty();
                $.each(cities, function (index, city) {
                    citiesSelect.append($('<option/>', {
                        value: city.value,
                        text: city.text
                    }));
                });
            });
        });
    });
</script>

Save the changes. Run the application, and it should work as expected.

In the next article, I will discuss Areas in ASP.NET Core MVC with an Example. In this article, I explain How to Implement Cascading Dropdown List in ASP.NET Core MVC using jQuery AJAX with an Example. I hope you enjoy this article: How to Implement Cascading Dropdown List in ASP.NET Core MVC using jQuery AJAX.

Leave a Reply

Your email address will not be published. Required fields are marked *