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

ASP.NET中JS数组赋值给C# List为空的问题排查

问题原因及解决方法

1. JS提交的数据格式不匹配模型绑定要求

你的视图模型里SelectedStations是List<int>类型,但JS里创建的是包含StationId属性的对象数组(比如[{StationId:1}, {StationId:2}]),ASP.NET默认模型绑定无法直接将这种对象数组映射到List<int>。

解决方法:
把JS里的数组转换成纯数值数组:

// 原代码示例
const stations = [{StationId: 1}, {StationId: 2}];
// 转换为纯int数组
const selectedStations = stations.map(item => item.StationId);

提交时将SelectedStations对应这个纯数值数组。

2. Ajax请求未正确设置内容类型

如果提交JSON格式数据,必须设置contentType: "application/json; charset=utf-8",否则ASP.NET无法正确解析JSON数据。

示例Ajax代码:

$.ajax({
    url: '/Test/Create',
    type: 'POST',
    contentType: 'application/json; charset=utf-8', // 必须配置
    data: JSON.stringify({
        SelectedStations: selectedStations
        // 视图模型其他属性...
    }),
    success: function(response) {
        // 处理成功逻辑
    }
});

3. 控制器方法参数配置错误

确保控制器的Create方法标记[HttpPost]特性,且参数为你的视图模型类型:

[HttpPost]
public IActionResult Create(YourViewModel model)
{
    // 业务逻辑处理
    return View();
}

注意:提交的JSON顶级属性名要和视图模型的SelectedStations属性名完全一致(大小写敏感)。

4. 视图模型属性可访问性问题

确保SelectedStations是公共属性且包含getter和setter:

public class YourViewModel
{
    public List<int> SelectedStations { get; set; }

    // 构造函数初始化列表
    public YourViewModel()
    {
        SelectedStations = new List<int>();
    }
}

私有属性或无setter会导致模型绑定无法赋值。

5. 表单格式提交的索引格式问题(非JSON场景)

如果用传统表单格式(application/x-www-form-urlencoded)提交,需要把数组转换成带索引的格式:

const formData = new FormData();
selectedStations.forEach((id, index) => {
    formData.append(`SelectedStations[${index}]`, id);
});
// 添加其他视图模型属性

$.ajax({
    url: '/Test/Create',
    type: 'POST',
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
        // 处理逻辑
    }
});

这种方式适合混合文件上传的场景,纯数据提交优先用JSON格式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:25:18