`描述:
我正在开发一个项目,需要使用 AJAX 在 ASP.NET Core 中实现级联下拉菜单。目标是为国家/地区、州/省和城市创建三个下拉列表,其中选择国家/地区应填充相应的州,选择州/省应显示相关城市。
我已经设置了控制器来处理 AJAX 请求,并使用必要的 HTML 和 JavaScript 配置了视图。但是,我在尝试使用 AJAX 获取州和城市时遇到 404 错误。`
Controller Code (Extract from LecturerController):-
[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 可能存在问题。当我从下拉列表中选择一个国家/地区时,我遇到了 404 错误,当我选择一个州时也会发生同样的情况。
值得注意的是,当我在下拉列表中选择“印度”时,它会填充三个“未定义”选项,即使数据库中有印度的三个州。
我对编程相对较新,因此任何有关解决此问题并成功实现级联下拉菜单的指导或建议将不胜感激。
感谢您的帮助!`