You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core中AJAX级联下拉框加载失败(404错误)

解决方案:ASP.NET Core三级级联下拉框404与Undefined问题

一、解决404错误

1. 修正路由与控制器命名匹配

你的控制器类是LecturerController,ASP.NET Core默认路由规则是去掉Controller后缀,所以路由中的控制器名称应该是Lecturer而非Lecturers,修改控制器路由特性:

[HttpGet]
[Route("Lecturer/GetStatesByCountry/{CountryID}")] // 改为单数Lecturer
public IActionResult GetStatesByCountry(int CountryID)
{
    // ...原有逻辑
}

[HttpGet]
[Route("Lecturer/GetCitiesByState/{StateID}")]
public JsonResult GetCitiesByState(int StateID)
{
    // ...原有逻辑
}

2. 使用Url.Action生成可靠URL

避免硬编码路径导致的根目录或部署路径问题,前端AJAX请求改用Url.Action生成正确地址:

// 替换原有的$.get路径
$.get('@Url.Action("GetStatesByCountry", "Lecturer")', { CountryID: selectedCountry }, function(data) {
    // ...原有逻辑
})

二、解决下拉框显示Undefined问题

1. 检查数据映射与数据库查询

出现三个undefined说明接口返回了3条数据,但Key/Value字段为空:

  • 调试dbAccessLayer.GetStatesByCountryID(CountryID)方法,确认返回的State对象中StateID和StateName属性有值;
  • 检查实体类State的属性名是否与数据库字段匹配,比如是否是StateId(驼峰)而非StateID(帕斯卡),导致映射失败。

2. 优化前端初始化与空值处理

页面加载时默认无选中国家,此时调用接口会请求无效参数,导致异常数据:

function updateStateDropdown() {
    var selectedCountry = document.getElementById("CountryID").value;
    var stateDropdown = document.getElementById("StateID");
    var cityDropdown = document.getElementById("CityID");

    // 重置下拉框
    stateDropdown.innerHTML = '<option value="">Select State</option>';
    cityDropdown.innerHTML = '<option value="">Select City</option>';

    // 未选择国家时不发送请求
    if (!selectedCountry) return;

    $.get('@Url.Action("GetStatesByCountry", "Lecturer")', { CountryID: selectedCountry }, function(data) {
        $.each(data, function(index, item) {
            var option = document.createElement("option");
            option.value = item.Key || "";
            option.text = item.Value || "Unknown State"; // 处理空值
            stateDropdown.appendChild(option);
        });
    }).fail(function(jqXHR) {
        console.log("请求失败,状态码:" + jqXHR.status);
    });
}

// 初始化时不再自动调用,仅在用户选择国家后触发
// updateStateDropdown();
// updateCityDropdown();

三、排查辅助步骤

  1. 打开浏览器开发者工具(F12)→ Network标签,查看AJAX请求的:
    • 实际请求URL是否与控制器路由匹配;
    • Response内容是否为预期的JSON数据,而非404错误页面。
  2. 在控制器方法中添加调试日志,确认参数接收和数据查询结果:
public IActionResult GetStatesByCountry(int CountryID)
{
    Console.WriteLine($"收到CountryID:{CountryID}");
    List<State> states = dbAccessLayer.GetStatesByCountryID(CountryID);
    Console.WriteLine("查询到州数量:" + states.Count);
    // ...原有逻辑
}

内容的提问来源于stack exchange,提问作者Sashank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:20:57