ASP .NET Core中Radio按钮选中值无法传递到Model问题求助
问题原因
ASP.NET Core的模型绑定依赖表单字段的name属性与模型属性名严格匹配,你在所有评分单选按钮上手动添加了name="servScore",覆盖了asp-for标签助手自动生成的name="GivenServiceScore"属性,导致提交的表单字段名和模型的GivenServiceScore属性无法匹配,属性只能取到int类型的默认值0。
修复方法
- 删除所有评分单选按钮上手动声明的
name="servScore"属性,保留asp-for="GivenServiceScore"即可,标签助手会自动生成正确的name值完成绑定 - 额外规范优化:删除所有单选按钮上重复的
id="servScore"属性,同一页面内不允许出现重复ID,asp-for会自动为每个单选按钮生成唯一ID,不影响正常使用
修复后的单选按钮代码示例:
@model MyProject.ViewModels.UserScoreModel <div> <label asp-for="GivenServiceScore"></label><br /> <input required asp-for="GivenServiceScore" type="radio" value="5" /> 5 <input required asp-for="GivenServiceScore" type="radio" style="padding-left:15px" value="4" /> 4 <input required asp-for="GivenServiceScore" type="radio" style="padding-left:15px" value="3" /> 3 <input required asp-for="GivenServiceScore" type="radio" style="padding-left:15px" value="2" /> 2 <input required asp-for="GivenServiceScore" type="radio" style="padding-left:15px" value="1" /> 1 <span asp-validation-for="GivenServiceScore" class="text-danger"></span> </div> <!-- 其余代码无需修改 -->
内容的提问来源于stack exchange,提问作者witchgen
相关产品推荐
相关产品推荐

