【发布时间】:2021-04-21 06:30:28
【问题描述】:
我正在尝试在 ASP.NET Core 3.1 中使用 jQuery 和 Ajax 创建级联下拉列表,但似乎无法找到解决方案。
这些是我的模型类:
public class CountryStateViewModel
{
public int CountryId { get; set; }
public int StateId { get; set; }
}
public class Country
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
public class State
{
public int CountryId { get; set; }
public int StateId { get; set; }
public string StateName { get; set; }
}
这些是我的控制器方法:
public ActionResult DropDown()
{
List<Country> CountryList = new List<Country> { new Country { CountryId = 1, CountryName = "Sweden" }, new Country { CountryId = 2, CountryName = "Norway" } };
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
public JsonResult GetStateList(int CountryId)
{
List<State> StateList = new List<State> { new State { StateId=1,CountryId = 1, StateName = "Stockholm" }, new State { CountryId = 1, StateName = "Malmö", StateId=2 } };
return Json(StateList);
}
这是我对脚本的看法:
<div class="container">
<div class="form-group">
@if (ViewBag.CountryList != null)
{
@Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select Country--", new { @class = "form-control" })
}
</div>
<div class="form-group">
@Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new { @class = "form-control" })
</div>
</div>
<script src="~/https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Forum/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "</option>")
});
});
})
});
</script>
最后,我尝试通过以下方式配置我的 startup.cs,以便它处理发送 JSON 对象:
services.AddControllers().AddNewtonsoftJson();
我无法完成这项工作。我想知道问题是否与调用脚本有关?这些是我在 Chrome 的开发者工具的控制台选项卡下看到的错误:
jquery.unobtrusive-ajax.min.js:1 Failed to load resource: the server responded with a status of 404 ()
jquery.min.js:1 Failed to load resource: the server responded with a status of 404 ()
jquery.min.js:1 Failed to load resource: the server responded with a status of 404 ()
jquery.unobtrusive-ajax.min.js:1 Failed to load resource: the server responded with a status of 404 ()
当我开始查看时,我可以看到两个下拉列表,但是当我选择一个国家/地区时,第二个下拉列表中没有显示任何州(只有两个选项说明未定义)。
【问题讨论】:
-
对不起!我正在使用 .NET Core 3.1。
-
有~有什么区别吗?
$.get("~/Forum/GetStateList", -
不幸的是:/。不过感谢您的建议。
标签: c# asp.net-core-mvc