ASP.NET Razor Page复选框绑定失败:Post提交后列表始终为空
问题原因
当前的复选框配置不符合ASP.NET Core模型绑定规则,导致Post请求时无法正确绑定数据:
- 复选框未设置
value属性,提交时没有传递具体的CubeName值; 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
相关产品推荐
相关产品推荐

