asp.net 未填充选项

xmd2e60i  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(127)

标题:AJAX在ASP.NET Core中的层叠下拉问题(404错误)

`说明:
我正在做一个项目,需要使用AJAX在ASP.NET Core中实现级联下拉菜单。目标是为Country、State和City创建三个下拉菜单,选择国家应该填充相应的州,选择州应该显示相关的城市。
我已经设置了控制器来处理AJAX请求,并使用必要的HTML和JavaScript配置了视图。但是,当我试图使用AJAX获取州和城市时,我遇到了404错误。
第一个月

[HttpGet]
        [Route("Lecturers/GetStatesByCountry/{CountryID}")]
        public IActionResult GetStatesByCountry(int CountryID)
        {
            // Replace this with your logic to fetch states based on the countryID.
            List<State> states = dbAccessLayer.GetStatesByCountryID(CountryID);

            // Convert the list of states to a format that can be easily serialized to JSON.
            var stateList = states.Select(s => new { Key = s.StateID, Value = s.StateName });

            return Json(stateList);
        }

        [HttpGet]
        [Route("Lecturers/GetCitiesByState/{StateID}")]
        public JsonResult GetCitiesByState(int StateID)
        {
            List<StudentP.Models.City> cities = dbAccessLayer.GetCitiesByStateID(StateID);
            var cityList = cities.Select(c => new { Key = c.CityID, Value = c.CityName }).ToList();
            return Json(cityList);
        }

字符串
View Code:-

@model StudentP.Models.LecturersModel
@using Microsoft.AspNetCore.Mvc.Rendering

@{
    ViewData["Title"] = "Create";
}

@using (Html.BeginForm("Create", "Lecturers", FormMethod.Post))
{
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Create Lecturer</title>
        <!-- Include Bootstrap CSS -->
        <link id="theme-link" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css" integrity="sha512-+w5jrxF5Tl2M9z6zweF98Cc5wPwP71A66f+OWiv60lgG1G9HjGjznfcLB8/aVvIs2hTfbj7z3VQgBEN8SP6KYg==" crossorigin="anonymous" />
        <!-- Include Font Awesome CSS for icons -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-ApNbghDs4vEX71nKGjW1rBq2v3Qxss3q5Dx9juYbfc4z3P8h6blVpz3x8M8A2FpxsdzU+Uug7c3dDlPZZXnZ6Lw==" crossorigin="anonymous" />

        <!-- Your custom CSS styles -->
        <link rel="stylesheet" href="your-custom-styles.css" />

        <!-- Dark Mode Toggle Button -->
        <style>
            /* Define a custom dark mode class */
            body {
                transition: background-color 0.5s, color 0.5s;
                position: relative;
                background: linear-gradient(to bottom, #ccc, #333);
                color: #eee;
            }

            body.dark-mode {
                background: #333;
                color: #fff;
            }

            #dark-mode-toggle {
                position: fixed;
                bottom: 20px;
                right: 20px;
                z-index: 9999;
            }
        </style>
    </head>
    <body>
        <div class="container mt-5">
            <div class="row mb-3">
                <div class="col-md-12">
                    <a class="minimal-button" asp-action="Create">Create New</a>
                    <a class="minimal-button" href="javascript:history.back();">Back</a>
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-12">
                    <h1>Create Lecturer</h1>
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-4">
                    <form asp-action="Create">
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                        <div class="form-group">
                            <label asp-for="FirstName" class="control-label">First Name</label>
                            <input asp-for="FirstName" class="form-control" />
                            <span asp-validation-for="FirstName" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            <label asp-for="LastName" class= "control-label">Last Name</label>
                            <input asp-for="LastName" class="form-control" />
                            <span asp-validation-for="LastName" class="text-danger"></span>
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.CountryID, "Country")
                            @Html.DropDownListFor(model => model.CountryID, ViewBag.Country as SelectList, "Select Country", new { @class = "form-control", id = "CountryID" })
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(model => model.StateID, "State")
                            @Html.DropDownListFor(model => model.StateID, ViewBag.States as SelectList, "Select State", new { @class = "form-control", id = "StateID" })
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(model => model.CityID, "City")
                            @Html.DropDownListFor(model => model.CityID, ViewBag.Cities as SelectList, "Select City", new { @class = "form-control", id = "CityID" })
                        </div>

                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">Create</button>
                            <a class="btn btn-secondary btn-lg btn-block" href="javascript:history.back();">Back</a>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Dark Mode Toggle Button -->
            <button id="dark-mode-toggle" class="btn btn-primary">Toggle Dark Mode</button>
        </div>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha512-d7I2WYT6F3RM1fD0dJ7b5AO0MvtA0bB9zTj16QKrq5KJDONBZg4z8lqrV5k3F/C6q0fs17IC3UZ5Yb4OgYms6tZw==" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js" integrity="sha512-6cXGp4d5PzR0eC+ZvApK1xID5Vy2XsXpB53dJPMTvIv/yzHzpk2Oi8gY4pF3x67bH7aGrb1a0ir8uG1mYcqr/Xw==" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js" integrity="sha512-AGV1fOtuAX+IiWXaemgak5tuU0+hh5+dPCa6Z6FgsqEq/UJGn3+nIO91MVp2g69sMWHdF/VtTa9/i7s7Q9/66w==" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>

        @section scripts {
        <script>
            function updateStateDropdown() {
                var selectedCountry = document.getElementById("CountryID").value;
                var stateDropdown = document.getElementById("StateID");

                // Clear the current options in the State dropdown
                stateDropdown.innerHTML = "";

                // Make an AJAX request to fetch the states based on the selected country
                $.get(`/Lecturers/GetStatesByCountry/${selectedCountry}`, function (data) {
                    // Create an option for each state
                    for (var i = 0; i < data.length; i++) {
                        var option = document.createElement("option");
                        option.value = data[i].Key;
                        option.text = data[i].Value;
                        stateDropdown.appendChild(option);
                    }

                    // Clear the city dropdown
                    var cityDropdown = document.getElementById("CityID");
                    cityDropdown.innerHTML = '<option value="">Select City</option>';
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    console.log("Error fetching states: " + errorThrown);
                });
            }

            function updateCityDropdown() {
                var selectedState = document.getElementById("StateID").value;
                var cityDropdown = document.getElementById("CityID");

                // Make an AJAX request to fetch the cities based on the selected state
                $.get(`/Lecturers/GetCitiesByState/${selectedState}`, function (data) {
                    cityDropdown.innerHTML = '<option value="">Select City</option>';
                    $.each(data, function (index, item) {
                        var option = document.createElement("option");
                        option.value = item.Key;
                        option.text = item.Value;
                        cityDropdown.appendChild(option);
                    });
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    console.log("Error fetching cities: " + textStatus);
                });
            }

            document.getElementById("CountryID").addEventListener("change", updateStateDropdown);
            document.getElementById("StateID").addEventListener("change", updateCityDropdown);

            // Initial update when loading the page
            updateStateDropdown();
            updateCityDropdown();
        </script>
    }

    </body>
    </html>
}


`这个问题似乎与AJAX请求有关。我怀疑AJAX请求中使用的URL可能有问题。当我从URL中选择一个国家时,我遇到404错误,当我选择一个州时也会发生同样的错误。
值得注意的是,当我在数据库中选择“India”时,它填充了三个“undefined”选项,尽管数据库中有三个印度州。
我是一个相对较新的编程者,所以我非常感谢任何关于解决这个问题和成功实现级联下拉菜单的指导或建议。
谢谢你的帮助!

eoigrqb6

eoigrqb61#

我测试你的代码并复制它,你可以尝试改变

option.value = data[i].Key;
 option.text = data[i].Value;
 option.value = item.Key;
 option.text = item.Value;

字符串
进入:

option.value = data[i].key;
option.text = data[i].value;
option.value = item.key;
option.text = item.value;


结果:

相关问题