Implementing Cascading Drop-Down Lists in .NET Core

When developing web applications, especially those that handle a fair amount of user input and interaction, enhancing user experience becomes paramount. One common scenario is when the user needs to select data from multiple related categories. This is where cascading drop-down lists come into play, significantly simplifying the process by narrowing down the user's choices based on their previous selections. This method not only improves the efficiency of data entry but also helps in maintaining the relevance of the user's choices.

Background and Requirements

The requirement for cascading drop-down lists often arises in applications dealing with geographical data, such as addresses, or any scenario where data is hierarchically structured. For instance, a user selecting a car make can then be prompted to select from models specifically of that make. This idea can be extended to numerous other applications, such as online shopping, booking systems, or any form-based applications.

This functionality was specifically requested by a client who wanted to streamline their data entry process for an inventory management system. They noticed that users were often overwhelmed by the large number of unrelated options and it was slowing down their workflow. Implementing cascading drop-down lists was the optimal solution to ensure that users first select a general category, which then filters the subsequent options in the related category.

Objectives

The primary objectives for implementing cascading drop-down lists in this project are,

  1. Improve User Experience: Reduce the cognitive load on users by limiting their choices to relevant options, thereby speeding up the decision-making process.
  2. Increase Data Accuracy: By guiding the user through a controlled data entry path, the chances of data entry errors are minimized.
  3. Enhance Application Efficiency: Streamline the interaction and reduce the amount of time taken to fill out forms, making the application more efficient to use.

Implementation in .NET Core

.NET Core, with its MVC architecture, provides a robust framework for building scalable and maintainable web applications. Its separation of concerns makes it an ideal choice for implementing features like cascading drop-down lists, where the model, view, and controller can be distinctly managed.

Environment Setup

To follow this tutorial, ensure you have the following.

  • .NET Core 3.1 SDK or later.
  • Visual Studio 2019 or a similar IDE that supports .NET Core development.

The following steps outline how to implement cascading drop-down lists in a .NET Core application, using a simple example of countries and cities.

Steps to Implement Cascading Drop-Down Lists

  • Step 1: Create a New .NET Core MVC Project
  • Step 2: Define the Models
  • Step 3: Create the Controller
  • Step 4: Create the View

Each step involves specific tasks like setting up the project environment, defining the data models, writing the controller logic to handle client requests, and crafting the view to display the UI elements.

This structured approach not only meets the client's requirements but also adheres to the best practices in software development using .NET Core. By following these steps, developers can efficiently implement cascading drop-down lists tailored to their specific needs, thereby enhancing the overall functionality of their applications.

Step 1. Create a New .NET Core MVC Project

Start by creating a new .NET Core MVC project. Open Visual Studio, select "Create a new project," then choose "ASP.NET Core Web Application." Name your project, and ensure you select .NET Core and ASP.NET Core 3.1 (or later) for the framework.

Step 2. Define the Models

For our example, we’ll need two models: Country and City. Each country will have multiple cities. Here’s how to define these models.

public class Country
{
    public int CountryId { get; set; }
    public string Name { get; set; }
    public List<City> Cities { get; set; }
}

public class City
{
    public int CityId { get; set; }
    public string Name { get; set; }
    public int CountryId { get; set; } // Foreign key
}

Step 3. Create the Controller

Add a new controller named DropdownController. This controller will handle fetching data for our drop-downs.

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

public class DropdownController : Controller
{
    private List<Country> countries = new List<Country>
    {
        new Country { CountryId = 1, Name = "United States", Cities = new List<City>
            {
                new City { CityId = 1, Name = "New York", CountryId = 1 },
                new City { CityId = 2, Name = "Los Angeles", CountryId = 1 }
            }
        },
        new Country { CountryId = 2, Name = "Canada", Cities = new List<City>
            {
                new City { CityId = 3, Name = "Toronto", CountryId = 2 },
                new City { CityId = 4, Name = "Vancouver", CountryId = 2 }
            }
        }
    };

    public IActionResult Index()
    {
        ViewBag.Countries = countries;
        return View();
    }

    public IActionResult GetCities(int countryId)
    {
        var cities = countries.FirstOrDefault(c => c.CountryId == countryId)?.Cities;
        return Json(cities);
    }
}

Step 4. Create the View

Now, create a view Index.cshtml under Views/Dropdown and add the following HTML and JavaScript.

@{
    ViewData["Title"] = "Cascading Dropdown Demo";
}

<h2>@ViewData["Title"]</h2>

<select id="countryDropdown">
    <option value="">Select a Country</option>
    @foreach (var country in ViewBag.Countries)
    {
        <option value="@country.CountryId">@country.Name</option>
    }
</select>

<select id="cityDropdown">
    <option value="">Select a City</option>
</select>

@section Scripts {
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $('#countryDropdown').change(function () {
            var countryId = $(this).val();
            $('#cityDropdown').empty();
            $('#cityDropdown').append('<option value="">Select a City</option>');
            $.getJSON('@Url.Action("GetCities", "Dropdown")', { countryId: countryId }, function (cities) {
                $.each(cities, function (index, city) {
                    $('#cityDropdown').append($('<option>', {
                        value: city.cityId,
                        text: city.name
                    }));
                });
            });
        });
    </script>
}

This code sets up two drop-down menus. When a country is selected, it triggers a JavaScript function that fetches the cities for that country using the GetCities action and populates the second drop-down.

Conclusion

Cascading drop-down lists can significantly enhance the user experience by simplifying data entry and selection processes. This guide demonstrates a basic implementation in a .NET Core application. You can extend this by integrating with a database and adding more dynamic content based on your application's requirements.


Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.