I need to have multiple radio button groups in my form like this:
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;}
}
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
all you need is to tie the group to a different item in your model
I fixed a similar issue building a RadioButtonFor with pairs of text/value from a SelectList. I used a ViewBag to send the SelectList to the View, but you can use data from model too. My web application is a Blog and I have to build a RadioButton with some types of articles when he is writing a new post.
The code below was simplyfied.
In the View, I used a foreach to build a radiobutton.
Notice that I used RadioButtonFor in order to catch the option value selected by user, in the Controler, after submit the form. I also had to put the item.Text outside the RadioButtonFor in order to show the text options.
Hope it's useful!
You can use Dictonary to map Assume Milk,Butter,Chesse are group A (ListA) Water,Beer,Wine are group B
At View , you can foreach Keys in dataMap and process your action
Ok here's how I fixed this
My model is a
list
of categories. Each category contains alist
of its subcategories.with this in mind, every time in the foreach loop, each
RadioButton
will have its category's ID (which is unique) as its name attribue.And I also used
Html.RadioButton
instead ofHtml.RadioButtonFor
.Here's the final 'working' pseudo-code:
The result is:
Please note that I HAVE NOT put all these radio button groups inside a form. And I don't know if this solution will still work properly in a form.
Thanks to all of the people who helped me solve this ;)