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

如何向POST控制器传递含List<int>成员的模型?为何List数据丢失?

问题原因与解决方案

你的问题出在表单字段的命名不符合ASP.NET MVC模型绑定的集合解析规则,以及错误使用Html.HiddenFor的方式:

错误分析

你当前的循环代码会生成多个name="ids"的隐藏字段,提交后表单数据格式为ids=1&ids=2&ids=3(假设你的ids列表是[1,2,3])。默认情况下,ASP.NET MVC的模型绑定器无法将这种重复同名的参数自动转换为List<int>,最终导致接收端得到空列表。

另外,Html.HiddenFor(model => model.ids)本身是针对整个集合属性生成字段,而非集合中的单个元素,手动覆盖name和value只会进一步破坏模型绑定的规则。

正确实现方式

方式1:使用for循环(推荐)

利用集合的索引器,让Html.HiddenFor自动生成符合模型绑定规则的字段名:

@for (int i = 0; i < Model.ids.Count; i++)
{
    @Html.HiddenFor(m => m.ids[i])
}

这段代码会生成类似以下的HTML:

<input type="hidden" name="ids[0]" value="1" />
<input type="hidden" name="ids[1]" value="2" />
<input type="hidden" name="ids[2]" value="3" />

带索引的命名格式ids[N]是模型绑定器识别集合的标准格式,能正确将提交的值组装为List<int>。

方式2:手动构造隐藏字段(foreach循环场景)

如果必须使用foreach,可以手动维护索引并构造正确的字段名:

@{ int index = 0; }
@foreach (var id in Model.ids)
{
    <input type="hidden" name="ids[@index]" value="@id" />
    index++;
}

额外注意事项

  • 确保你的模型中ids属性是public且带有get/set访问器:
    public class YourModel
    {
        public List<int> ids { get; set; }
        // 其他属性...
    }
    
  • 控制器的POST方法参数要正确接收模型:
    [HttpPost]
    public IActionResult YourAction(YourModel model)
    {
        // 此时model.ids应能正确获取提交的值
        // ...
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:50:29