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

ASP.NET Razor Page复选框绑定失败:Post提交后列表始终为空

问题原因

当前的复选框配置不符合ASP.NET Core模型绑定规则,导致Post请求时无法正确绑定数据:

  1. 复选框未设置value属性,提交时没有传递具体的CubeName值;
  2. name属性格式错误,模型绑定器无法识别该格式对应的CubeList集合对象。
解决方案

方案1:直接绑定选中的CubeName列表(推荐,更轻量)

如果仅需获取选中的Cube名称,可简化后端属性并调整前端代码:

后端修改

[BindProperty] 
public IList<string> SelectedCubes { get; set; } = new List<string>();

前端修改

@foreach (var item in Model.CubeList)
{
    <label id="label_@item.CubeName" class="control-label">
        <input type="checkbox" class="radio-inline" name="SelectedCubes" id="@item.CubeName" value="@item.CubeName" />
        @item.CubeName
    </label>
}

提交后,SelectedCubes会自动填充所有选中的CubeName值。

方案2:绑定完整的CubeTableInDatabase集合(需添加选中标记)

如果需要绑定完整对象集合并标记选中状态,需为模型添加选中属性,同时调整前端name格式:

模型修改

public class CubeTableInDatabase
{
    [Key]
    public string? CubeName { get; set; }
    public bool IsSelected { get; set; } // 添加选中标记属性
}

前端修改

@for (int i = 0; i < Model.CubeList.Count; i++)
{
    <label id="label_@Model.CubeList[i].CubeName" class="control-label">
        <!-- 用索引式name让模型绑定器识别集合项 -->
        <input type="checkbox" class="radio-inline" name="CubeList[@i].IsSelected" id="@Model.CubeList[i].CubeName" 
               checked="@Model.CubeList[i].IsSelected" />
        <!-- 隐藏域传递CubeName,确保对象标识不丢失 -->
        <input type="hidden" name="CubeList[@i].CubeName" value="@Model.CubeList[i].CubeName" />
        @Model.CubeList[i].CubeName
    </label>
}

注意需用for循环而非foreach,这样才能生成带索引的name属性(如CubeList[0].IsSelected);同时通过隐藏域传递CubeName,保证每个集合项的标识能被正确绑定。提交后,CubeList中每个对象的IsSelected会对应复选框的选中状态。

关键说明
  • ASP.NET Core绑定集合时,要么使用带索引的name格式(针对复杂对象集合),要么直接绑定简单类型列表(如字符串、数字);
  • 复选框必须设置value属性,未选中的复选框不会被提交到后端。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:05:27