Home >Backend Development >C++ >How Can I Efficiently Load Dependent Dropdowns (State and City) in MVC Using Unobtrusive JavaScript?

How Can I Efficiently Load Dependent Dropdowns (State and City) in MVC Using Unobtrusive JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2025-01-28 18:26:09714browse

How Can I Efficiently Load Dependent Dropdowns (State and City) in MVC Using Unobtrusive JavaScript?

Optimized the plan for loading the double drop -down menu in the MVC

Traditionally, loading the state and urban drop -down menu in the MVC application requires the combination of the controller operation and the JavaScript code. Although this method is effective, it may be tedious and easy to make mistakes. Let us explore a more efficient and more powerful way to deal with this task.

Using view models and non -invasive javascript

Instead of coding the drop -down menu in the view, it is better to introduce a view model to contain all the necessary data. In addition, we will use non -invasive JavaScript to enhance user experience without pollution marking.

View model

Controller operation

<code class="language-csharp">public class PersonViewModel
{
    public int StateID { get; set; }
    public int CityID { get; set; }
    public List<SelectListItem> States { get; set; }
    public List<SelectListItem> Cities { get; set; }
}</code>
In the controller operation, we will prepare the view model and pass it to the view.

View

In the view, we will use the
<code class="language-csharp">public ActionResult Index()
{
    var states = GetStates().Select(s => new SelectListItem { Value = s.Id.ToString(), Text = s.Name }).ToList();
    var cities = GetCities().Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Name }).ToList();
    var model = new PersonViewModel
    {
        States = states,
        Cities = cities
    };

    return View(model);
}</code>
helper to present the drop -down menu.

Non -invasive JavaScript

@Html.DropDownList Using jQuery, we can enhance the behavior of the state drop -down menu and dynamically load the city.

<code class="language-html">@model PersonViewModel

...

@Html.DropDownListFor(m => m.StateID, Model.States, "请选择州")
@Html.DropDownListFor(m => m.CityID, Model.Cities, "请选择城市")

...</code>

advantages

This method provides the following advantages:

<code class="language-javascript">$(document).ready(function() {
    $("#StateID").change(function() {
        var stateId = $(this).val();
        $.ajax({
            url: '@Url.Action("GetCities", "Home")',
            data: { stateId: stateId },
            success: function(response) {
                var citiesDropdown = $('#CityID');
                citiesDropdown.empty();
                citiesDropdown.append($("<option></option>").attr("value", "").text("请选择城市")); // 添加默认选项
                $.each(response, function(index, city) {
                    citiesDropdown.append($("<option></option>").attr("value", city.Id).text(city.Name));
                });
            }
        });
    });
});</code>
By eliminating the operation of multiple controllers, the complexity of the code is reduced.

Due to the separation of the focus between view models, controllers and views, it improves maintenance.

By improving the user experience by loading cities in the selected state.

Essable requests only when necessary to reduce the server load.
  • Note: The above code clips assume that
  • and
  • methods have existed and returned appropriate data, and
  • and
  • objects have
  • and
  • properties. The use of
also handled the drop -down menu option more standardized. After adding the default option ", select the city" and "Please select the state" to enhance the user experience.

The above is the detailed content of How Can I Efficiently Load Dependent Dropdowns (State and City) in MVC Using Unobtrusive JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn