This one has me stumped, I have a strongly typed view that has this loop to generate radiobuttons:
<% foreach (QuestionAnswer qa in Model.QuestionAnswers)
{ %>
<%= Html.RadioButtonFor(model => model.QuestionAnswers[(int)qa.QuestionID - 1].AnswerValue, "Checked" ) %>
<%= Html.Encode(qa.OptionValue) %>
<% } %>
It renders fine, but since the names are not the same, you can select more than 1 radiobutton. How can I group them so only 1 radiobutton can be selected?
Any help would be appreciated!
This question is related to
c#
asp.net
asp.net-mvc-2
In my case, I had a collection of radio buttons that needed to be in a group. I just included a 'Selected' property in the model. Then, in the loop to output the radiobuttons just do...
@Html.RadioButtonFor(m => Model.Selected, Model.Categories[i].Title)
This way, the name is the same for all radio buttons. When the form is posted, the 'Selected' property is equal to the category title (or id or whatever) and this can be used to update the binding on the relevant radiobutton, like this...
model.Categories.Find(m => m.Title.Equals(model.Selected)).Selected = true;
May not be the best way, but it does work.
In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.
Source: Stackoverflow.com