我的表单中需要有多个单选按钮组,如下所示:
我知道只需为每个组指定相同的“name”html 属性即可完成。
但是
在使用 html 帮助器时,MVC 不允许您指定自己的 name 属性,如下所示:
@Html.RadioButtonFor(i => item.id, item.SelectedID, new { Name = item.OptServiceCatId })
因为它会查看每个标签的“name”属性(而不是“id”)以将表单映射/绑定(bind)到模型 Controller 接收等。
有人说为每个组指定相同的“GroupName”属性可以解决问题,但这也不起作用。
那么,有什么有效的方法吗?
编辑:
这是我的观点(简化):
@model Service_Provider.ViewModels.SelectOptServicesForSubServiceViewModel
@foreach (var cat in Model.OptServices)
{
//A piece of code & html here
@foreach (var item in cat.OptItems.Where(i => i.MultiSelect == false))
{
@Html.RadioButtonFor(i => item.id, item.SelectedID, new { GroupName = item.OptServiceCatId })
<br />
}
}
注意:
我的型号是List<OptServices>
:
public List<OptServices> Cats {get; set;}
OptServices 有一个 List
的OptItems
里面:
public class OptServices
{
//a few things
public List<OptItems> Items {get; set;}
}
最佳答案
您所需要做的就是将组绑定(bind)到模型中的不同项目
@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")
@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")
关于asp.net-mvc-4 - MVC 4 Razor 中的多个单选按钮组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22174475/