Problem:
In an ASP.NET MVC 5 project, attempting to create multiple groups of radio buttons using a loop results in only one group being formed, deselecting previously selected options.
Code:
foreach(var question in Model.GeneralQuestions) { <div class = "well"> <h3> <strong>@question.QuestionString</strong> </h3> @foreach (var answer in question.PossibleAnswers) { @Html.RadioButtonFor(model => question.QuestionString, answer.Answer) @Html.Label(answer.Answer) <br /> } </div> }
Solution:
1. Use View Models:
Define view models that represent the data you want to display and edit. In this case, it is necessary to create view models for Questions and Subjects to represent the structure of your data model.
2. Generate Radio Buttons in a Loop:
Create a loop to generate the radio buttons. Each button should have a unique name attribute based on its question and subject context. For example:
foreach (var subject in Model.Subjects) { @Html.HiddenFor(m => subject.ID) foreach (var question in subject.Questions) { @Html.HiddenFor(m => question.ID) <div> @Html.RadioButtonFor(m => subject.Questions[j].SelectedAnswer, answer.ID, new { id = answer.ID }) <label for="@answer.ID"> @answer.Text </label> </div> } }
3. Bind to Model Properties:
Ensure that the radio button name attribute correctly binds to a property in your model. Each group of radio buttons should have a separate property to hold the selected answer.
4. Adjust Controller Actions:
Modify the controller Edit action to populate the view model with values from the database and to handle the form submission by saving the selected answers.
Remember to check the HTML generated by the view to verify that the radio button name attributes are correctly structured for binding to your model on form submission.
The above is the detailed content of How to Properly Group Radio Buttons in ASP.NET MVC 5 Using Loops?. For more information, please follow other related articles on the PHP Chinese website!