search
HomeBackend DevelopmentC++How to Efficiently Load Cascading State and City Dropdowns in MVC using AJAX?

How to Efficiently Load Cascading State and City Dropdowns in MVC using AJAX?

The improved MVC double -drop -down list loading method

One way to load two drop -down lists (states and cities) in the MVC is to use the AJAX -level pull -up list method. The following is the improved code version:

Controller

View (using non -invasive javascript)

/// <summary>
/// 获取州列表
/// </summary>
/// <returns>州列表,SelectListItem类型</returns>
private IEnumerable<SelectListItem> GetStates()
{
    using (var db = new DataEntities())
    {
        return db.States.Select(d => new SelectListItem { Text = d.StateName, Value = d.Id.ToString() });
    }
}

/// <summary>
/// 获取指定州的城市列表
/// </summary>
/// <param name="id">州ID</param>
/// <returns>城市列表,JSON格式</returns>
[HttpGet]
public ActionResult GetCities(int id)
{
    using (var db = new DataEntities())
    {
        var data = db.Cities.Where(d => d.StateId == id).Select(d => new { Text = d.CityName, Value = d.Id }).ToList();
        return Json(data, JsonRequestBehavior.AllowGet);
    }
}

In this method, we use the operation method to retrieve the cities selected in the state and return it as JSON. On the client, we use non -invasive JavaScript to handle the

incident of the state drop -down list and dynamically fill the city's drop -down list. This method provides a better user experience without a complete page refresh. The code was improved, the
@model Person

@{
    ViewBag.Title = "Home Ajax";
    IEnumerable<Person> persons = ViewBag.Persons;
    IEnumerable<SelectListItem> States = ViewBag.States;
}

@section featured {
    <div class="content-wrapper">
        <hgroup class="title"><h1 id="ViewBag-Title">@ViewBag.Title</h1></hgroup>
    </div>
}

@section styles {
    td, th {
        border: 1px solid;
        padding: 5px 10px;
    }

    select {
        padding: 5px 2px;
        width: 310px;
        font-size: 16px;
    }
}

@section scripts {
    @Scripts.Render("~/bundles/jqueryval")

    <script>
        var cityStates = @Html.Raw(Json.Encode(ViewBag.CityStates)); // 将CityState JSON转换为JavaScript对象

        $(document).ready(function () {
            $("#ddlState").change(function () {
                loadCities(this);
            });
            loadCities($("#ddlState")[0]); // 页面加载时初始化城市下拉列表
        });


        function loadCities(obj) {
            var stateId = parseInt($(obj).val());
            var cities = cityStates.find(v => v.Id === stateId)?.Cities;

            if (cities) {
                fillCity(cities);
            } else {
                $("#ddlCity").empty(); // 清空城市下拉列表
            }
        }

        function fillCity(cities) {
            $("#ddlCity").empty(); // 清空城市下拉列表
            $.each(cities, function (index, city) {
                $("#ddlCity").append($("<option></option>").val(city.Id).text(city.CityName));
            });
        }

        function Edit(obj, Id) {
            $("input[name='Id']").val(Id);
            var tr = $(obj).closest("tr");
            $("#txtfirstName").val($("td[data-id='fn']", tr).text().trim());
            $("#txtlastName").val($("td[data-id='ln']", tr).text().trim());
            $("#txtemail").val($("td[data-id='email']", tr).text().trim());
            $("#ddlState").val($("td[data-id='cn'] input[type='hidden']", tr).val());
            loadCities($("#ddlState")[0]); // 更新城市下拉列表
        }
    </script>
}

<h3></h3>
situation of

was processed, and the filling method of the urban drop -down list was optimized. The initialization operation of the page loading is added to ensure that the city drop -down list is also correctly filled when the page is loaded. GetCities

The above is the detailed content of How to Efficiently Load Cascading State and City Dropdowns in MVC using AJAX?. 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
Mastering Polymorphism in C  : A Deep DiveMastering Polymorphism in C : A Deep DiveMay 14, 2025 am 12:13 AM

Mastering polymorphisms in C can significantly improve code flexibility and maintainability. 1) Polymorphism allows different types of objects to be treated as objects of the same base type. 2) Implement runtime polymorphism through inheritance and virtual functions. 3) Polymorphism supports code extension without modifying existing classes. 4) Using CRTP to implement compile-time polymorphism can improve performance. 5) Smart pointers help resource management. 6) The base class should have a virtual destructor. 7) Performance optimization requires code analysis first.

C   Destructors vs Garbage Collectors : What are the differences?C Destructors vs Garbage Collectors : What are the differences?May 13, 2025 pm 03:25 PM

C destructorsprovideprecisecontroloverresourcemanagement,whilegarbagecollectorsautomatememorymanagementbutintroduceunpredictability.C destructors:1)Allowcustomcleanupactionswhenobjectsaredestroyed,2)Releaseresourcesimmediatelywhenobjectsgooutofscop

C   and XML: Integrating Data in Your ProjectsC and XML: Integrating Data in Your ProjectsMay 10, 2025 am 12:18 AM

Integrating XML in a C project can be achieved through the following steps: 1) parse and generate XML files using pugixml or TinyXML library, 2) select DOM or SAX methods for parsing, 3) handle nested nodes and multi-level properties, 4) optimize performance using debugging techniques and best practices.

Using XML in C  : A Guide to Libraries and ToolsUsing XML in C : A Guide to Libraries and ToolsMay 09, 2025 am 12:16 AM

XML is used in C because it provides a convenient way to structure data, especially in configuration files, data storage and network communications. 1) Select the appropriate library, such as TinyXML, pugixml, RapidXML, and decide according to project needs. 2) Understand two ways of XML parsing and generation: DOM is suitable for frequent access and modification, and SAX is suitable for large files or streaming data. 3) When optimizing performance, TinyXML is suitable for small files, pugixml performs well in memory and speed, and RapidXML is excellent in processing large files.

C# and C  : Exploring the Different ParadigmsC# and C : Exploring the Different ParadigmsMay 08, 2025 am 12:06 AM

The main differences between C# and C are memory management, polymorphism implementation and performance optimization. 1) C# uses a garbage collector to automatically manage memory, while C needs to be managed manually. 2) C# realizes polymorphism through interfaces and virtual methods, and C uses virtual functions and pure virtual functions. 3) The performance optimization of C# depends on structure and parallel programming, while C is implemented through inline functions and multithreading.

C   XML Parsing: Techniques and Best PracticesC XML Parsing: Techniques and Best PracticesMay 07, 2025 am 12:06 AM

The DOM and SAX methods can be used to parse XML data in C. 1) DOM parsing loads XML into memory, suitable for small files, but may take up a lot of memory. 2) SAX parsing is event-driven and is suitable for large files, but cannot be accessed randomly. Choosing the right method and optimizing the code can improve efficiency.

C   in Specific Domains: Exploring Its StrongholdsC in Specific Domains: Exploring Its StrongholdsMay 06, 2025 am 12:08 AM

C is widely used in the fields of game development, embedded systems, financial transactions and scientific computing, due to its high performance and flexibility. 1) In game development, C is used for efficient graphics rendering and real-time computing. 2) In embedded systems, C's memory management and hardware control capabilities make it the first choice. 3) In the field of financial transactions, C's high performance meets the needs of real-time computing. 4) In scientific computing, C's efficient algorithm implementation and data processing capabilities are fully reflected.

Debunking the Myths: Is C   Really a Dead Language?Debunking the Myths: Is C Really a Dead Language?May 05, 2025 am 12:11 AM

C is not dead, but has flourished in many key areas: 1) game development, 2) system programming, 3) high-performance computing, 4) browsers and network applications, C is still the mainstream choice, showing its strong vitality and application scenarios.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft