ASP.NET Core如何将ViewModel中的列表绑定到单选按钮并正常提交
问题原因
ASP.NET Core的模型绑定器在绑定集合类型属性时,要求表单控件的name属性遵循集合属性名[索引].属性名的格式。你当前使用foreach遍历生成的单选按钮,要么手动指定了name为问题ID,要么自动生成的name不符合绑定规则,因此绑定器无法将提交的值映射到AllQuestions集合,导致其为null。
解决步骤
- 将
foreach遍历改为for循环:获取集合索引,用于生成符合规则的name属性 - 添加必要的隐藏域:存储不需要用户修改但提交时需要保留的属性(如问题ID、评估类型等)
- 修正单选按钮的绑定写法:删除手动指定的
name属性,使用asp-for指向带索引的集合属性,自动生成正确的name
修改后的视图核心代码
@if (Model.AllQuestions != null) { <!-- 保存AssessmentType等父级属性,避免提交后丢失 --> <input type="hidden" asp-for="AssessmentType" /> @for (int i = 0; i < Model.AllQuestions.Count; i++) { <!-- 存储当前问题的ID,提交后可以对应到具体题目 --> <input type="hidden" asp-for="@Model.AllQuestions[i].Id" /> <div class="row rclass"> <div class="col-lg-5 col-md-5 col-sm-12 qclass"> <h4 style="color: #08c7bf;">问题 @(i+1)</h4> <label class="text1">@Model.AllQuestions[i].Question</label> </div> <div class="col-lg-7 col-md-7 col-sm-12 oclass justify-content-center align-self-center"> <div class="row nclass"> <div class="col-lg-2 col-sm-4"> <h7>从不</h7><br> <input type="radio" asp-for="@Model.AllQuestions[i].Response" value="1" class="margin-top"> </div> <div class="col-lg-2 col-sm-4"> <h7>很少</h7><br> <input type="radio" asp-for="@Model.AllQuestions[i].Response" checked value="2" class="margin-top"> </div> <div class="col-lg-3 col-sm-4"> <h7>有时</h7><br> <input type="radio" asp-for="@Model.AllQuestions[i].Response" value="3" class="margin-top"> </div> <div class="col-lg-2 col-sm-4"> <h7>经常</h7><br> <input type="radio" asp-for="@Model.AllQuestions[i].Response" value="4" class="margin-top"> </div> <div class="col-lg-3 col-sm-4"> <h7>总是</h7><br> <input type="radio" asp-for="@Model.AllQuestions[i].Response" value="5" class="margin-top"> </div> </div> </div> </div> <hr> } }
注意事项
- 不要手动覆盖
asp-for生成的name属性,否则会破坏绑定规则 - 如果需要保留
AssessmentResponseViewModel中的其他字段(如TakenBy、DateTime),也需要在表单中添加对应的隐藏域存储值 - 同组单选按钮的
name属性会由asp-for自动生成一致的值,不需要手动指定,保证同一问题只能选一个选项
内容的提问来源于stack exchange,提问作者Åfsħąl Ãtħąr
相关产品推荐
相关产品推荐

