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

ASP.NET Core 3.1 级联下拉框jQuery Ajax返回值为undefined问题

问题根因

ASP.NET Core 3.1默认使用System.Text.Json作为JSON序列化组件,该组件默认会将返回对象的属性名转换为小驼峰格式:你后端返回的SelectListItem的Value、Text属性,序列化到前端后会变成value、text。你前端代码仍然用大写开头的location.Value、location.Text读取属性,自然取不到值,就会全部显示为undefined。

另外你的AJAX请求URL写死了/GetLocations/1属于冗余写法,和你后面传的data: { id: $("#DDLRegion").val() }重复,但该问题不会导致undefined的现象。

解决方案

方案1:修改前端取值逻辑(最简单)

直接将AJAX成功回调里的属性名改为小驼峰即可,修改后的jQuery代码如下:

$(document).ready(function () {
    $("#DDLRegion").change(function () {
        $("#DDLLocation").empty();
        $.ajax({
            type: 'GET',
            // 这里可以把末尾的1删掉,避免和后面传的id参数冲突
            url: '/GetLocations',
            dataType: 'json',
            data: { id: $("#DDLRegion").val() },
            success: function (locationsList) {
                $.each(locationsList, function (i,location) {
                    // 把Value改为value,Text改为text
                    $('#DDLLocation').append('<option value="'
                        + location.value + '">' +
                        location.text + '</option>');
                });
            },
            error: function (ex) {
                alert('Failed to retrieve locations');
            }
        });
        return false;
    })
});

方案2:修改后端序列化规则(保留原有属性大小写)

如果不想修改前端代码,可以在Startup.cs的ConfigureServices方法中配置JSON序列化规则,关闭驼峰命名转换:

public void ConfigureServices(IServiceCollection services)
{
    // 原有其他服务注册代码保留,添加下面的配置
    services.AddControllersWithViews()
        .AddJsonOptions(options =>
        {
            // 保留属性名称的原有大小写,不转驼峰
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });
}

可选优化点

你后端Controller代码中已经构造了List<SelectListItem>类型的locations集合,不需要再套一层SelectList返回,直接返回locations即可:

// 把原来的return Json(new SelectList(locations,"Value","Text"));改成下面的
return Json(locations);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 16:18:01