Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - Multiple radio button groups in MVC 4 Razor

I need to have multiple radio button groups in my form like this:
enter image description here

I know it's simply done by specifying the same "name" html attribute for each group.
HOWEVER
MVC doesn't let you specify your own name attribute when using html helper like this:

@Html.RadioButtonFor(i => item.id, item.SelectedID, new { Name = item.OptServiceCatId })  

Because it looks at each tag's "name" attribute (not "id") to map/bind the form to the model which the controller receives, etc.

Some said that specifying each with the same "GroupName" attribute will solve the problem, but it didn't work either.

So, is there any way which works ?

EDIT:
Here's my view (simplified):

@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 />
  }    
}

NOTE:
My model is a List<OptServices>:

public List<OptServices> Cats {get; set;}

And OptServices has a List of OptItems inside:

public class OptServices
{
//a few things
public List<OptItems> Items {get; set;}
}
question from:https://stackoverflow.com/questions/22174475/multiple-radio-button-groups-in-mvc-4-razor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

all you need is to tie the group to a different item in your model

@Html.RadioButtonFor(x => x.Field1, "Milk")
@Html.RadioButtonFor(x => x.Field1, "Butter")

@Html.RadioButtonFor(x => x.Field2, "Water")
@Html.RadioButtonFor(x => x.Field2, "Beer")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...