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

.NET Core Razor视图中列表对象布尔字段提交后未映射值问题求助

解决ASP.NET Core列表布尔字段模型绑定失败的问题

我来帮你搞定这个问题!你遇到的核心问题确实是模型绑定的命名规则以及冗余的隐藏字段导致的,下面一步步给你拆解和修正:

问题分析

  1. 错误的name属性:你手动给复选框设置了name=" @Model.UsersonHearing[i].UserID",这完全不符合ASP.NET Core模型绑定的要求——列表项的字段需要形如UsersonHearing[i].RestrictDocumentViewForCurrentDocument的命名,模型绑定器才能识别这是列表中第i个元素的对应字段。
  2. 冗余的隐藏字段冲突:你同时给RestrictDocumentViewForCurrentDocument加了一个HiddenFor,这会导致提交时:
    • 复选框选中时:提交true和隐藏字段的初始值,模型绑定器可能优先取后者;
    • 复选框未选中时:复选框不会提交值,但隐藏字段会提交初始值,导致新的选择永远不会生效。

修正后的CSHTML代码

@for (int i = 0; i < Model.UsersonHearing.Count; i++) { 
    <tr> 
        <td> @Model.UsersonHearing[i].BuiltFullName </td> 
        <td> @Model.UsersonHearing[i].EmailAddress </td> 
        <td> @Model.UsersonHearing[i].AttorneyRole </td> 
        <td> 
            <!-- 移除手动设置的name,让asp-for自动生成正确的绑定路径 -->
            <input asp-for="@Model.UsersonHearing[i].RestrictDocumentViewForCurrentDocument" type="checkbox" /> 
            @Html.HiddenFor(m => m.UsersonHearing[i].UserID) 
            @Html.HiddenFor(m => m.UsersonHearing[i].Hearing_UsersID) 
            @Html.HiddenFor(m => m.UsersonHearing[i].BuiltFullName) 
            <!-- 删除这个隐藏字段!它会覆盖复选框的新值 -->
            <!-- @Html.HiddenFor(Model => Model.UsersonHearing[i].RestrictDocumentViewForCurrentDocument) -->
        </td> 
    </tr> 
}

关键修改说明

  1. 依赖asp-for自动生成name:asp-for="@Model.UsersonHearing[i].RestrictDocumentViewForCurrentDocument"会自动生成类似name="UsersonHearing[0].RestrictDocumentViewForCurrentDocument"的属性,完美匹配模型绑定的规则。
  2. 移除布尔字段的隐藏输入:对于非可空布尔类型(你的RestrictDocumentViewForCurrentDocument是Boolean而非Boolean?),ASP.NET Core模型绑定会自动处理:
    • 复选框选中时:提交true;
    • 复选框未选中时:因为没有提交值,模型绑定器会自动将字段设为false。

额外补充(可选)

如果你的模型字段是可空布尔类型(Boolean?),未选中复选框时模型绑定不会自动设为false,这时候可以在复选框前加一个同名隐藏字段来兜底:

<input type="hidden" asp-for="@Model.UsersonHearing[i].RestrictDocumentViewForCurrentDocument" value="false" />
<input asp-for="@Model.UsersonHearing[i].RestrictDocumentViewForCurrentDocument" type="checkbox" />

这样未选中时会提交隐藏字段的false,选中时复选框的true会覆盖它。

后端验证

确保你的POST方法接收的是包含UsersonHearing列表的视图模型,比如:

[HttpPost]
public IActionResult UpdateHearingUsers(YourViewModel model)
{
    // 此时model.UsersonHearing中的RestrictDocumentViewForCurrentDocument已经是用户修改后的值
    // 后续处理逻辑...
    return View(model);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:48:14