如何在ASP.NET MVC中使用jQuery Ajax实现国家联动州列表?
问题排查与修正方案
你的代码核心问题是Ajax成功回调里的变量名不匹配,同时还有几处细节问题需要调整,以下是具体修正:
1. 视图(View)代码修正
主要修复回调变量名、下拉框默认选项、事件绑定范围(避免监听所有select):
<table> <tbody> <td> @Html.DropDownList("countryVal", (IEnumerable<SelectListItem>)ViewBag.countryVal, "Select Country", new { @id = "Country" }) </td> <td> <!-- 修复拼写错误,添加默认空选项 --> <select id="state"> <option value="">Select State</option> </select> </td> </tbody> </table> <script src="~/Scripts/jquery-3.6.3.min.js"></script> <script type="text/javascript"> $(document).ready(function () { // 只监听国家下拉框的change事件,避免影响其他select $("#Country").change(function () { // 获取选中项的value(即countryId),比传递名称更可靠 var selectedCountryId = $(this).val(); // 空值判断用val更准确 if (selectedCountryId) { $('#state').empty().append('<option value="">Select State</option>'); $.ajax({ type: 'POST', url: "/Home/GetStates", // 传递countryId,控制器对应调整参数 data: { countryId: selectedCountryId }, success: function (data) { if (data && data.length > 0) { // 把res改成data,和回调参数一致 $.each(data, function (i, item) { $('#state').append(new Option(item.stateName, item.stateId)); }); } else { $('#state').append('<option value="">No states found</option>'); } }, // 添加错误回调,方便调试 error: function(xhr, status, error) { console.error("请求失败:", error); $('#state').append('<option value="">Failed to load states</option>'); } }); } else { // 重置州下拉框 $('#state').empty().append('<option value="">Select State</option>'); } }); }); </script>
2. 控制器(Controller)代码修正
调整参数接收为countryId,简化查询逻辑并避免空引用错误:
public ActionResult DropDown() { using (Db db = new Db()) { ViewBag.countryVal = new SelectList(db.Countries.ToList(), "countryId", "CountryName"); return View(); } } [HttpPost] public JsonResult GetStates(int countryId) { using (Db db = new Db()) { // 直接用countryId查询州,高效且避免名称重复问题 List<State> stateList = db.States.Where(x => x.countryId == countryId).ToList(); return Json(stateList, JsonRequestBehavior.AllowGet); } }
关键修正点说明
- 变量名错误:原代码中
success: function (data)但循环用了$.each(res, ...),把res改成data即可正确遍历返回的JSON数据。 - 传递ID而非名称:国家名称可能存在重复,传递
countryId(下拉框的value)更可靠,同时减少数据库查询的复杂度。 - 空值判断与重置:当未选择国家时,重置州下拉框为默认状态;请求失败时给出明确提示。
- 避免全局select监听:原代码
$("select").change()会监听页面所有下拉框,改成$("#Country").change()只监听国家下拉框,避免意外触发。
内容的提问来源于stack exchange,提问作者Riyaz Shaikh
相关产品推荐
相关产品推荐

