Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;} } 
like image 399
Ali Avatar asked Mar 04 '14 14:03

Ali


People also ask

Can you have multiple radio buttons?

Only one radio button in a group can be selected at the same time. Note: The radio group must have share the same name (the value of the name attribute) to be treated as a group.

How do you add a radio button to a razor?

Razor Radio Buttons. Razor offers two ways to generate radio buttons. The recommended approach is to use the input tag helper. When creating a radio button, you must provide the value of one of the predefined options to the value attribute.

How do you add radio buttons to groups?

You group radio buttons by drawing them inside a container such as a Panel control, a GroupBox control, or a form. All radio buttons that are added directly to a form become one group. To add separate groups, you must place them inside panels or group boxes.

Which property is for to set a grouping to RadioButton?

Use the GroupName property to specify a grouping of radio buttons to create a mutually exclusive set of controls. You can use the GroupName property when only one selection is possible from a list of available options. When this property is set, only one RadioButton in the specified group can be selected at a time.


1 Answers

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") 
like image 83
Matt Bodily Avatar answered Oct 04 '22 17:10

Matt Bodily