Home >Backend Development >C++ >How to Properly Group Radio Buttons by Question in ASP.NET MVC 5?
Issue:
When grouping radio buttons by question in an ASP.NET MVC 5 view, all radio buttons are placed in a single group, making it impossible to select answers for multiple questions independently.
Solution:
To properly group radio buttons, you need to ensure that each question has a unique name attribute. This can be achieved by using loop indices and view models to bind the radio buttons to a typed model.
View Model:
First, create view models that will be used to represent the data and generate the form.
public class QuestionVM { public int ID { get; set; } public string Text { get; set; } public int? SelectedAnswer { get; set; } } public class SubjectVM { public int? ID { get; set; } public string Name { get; set; } public List<QuestionVM> Questions { get; set; } } public class StudentVM { public int ID { get; set; } public string Name { get; set; } public List<SubjectVM> Subjects { get; set; } }
View:
In the view, use the @Html.BeginForm method to create a form element and then generate the radio buttons using the @Html.RadioButtonFor method.
@model YourAssembly.StudentVM @using(Html.BeginForm()) { // Hidden field for unique student identifier @Html.HiddenFor(m => m.ID) // Student name (with no binding) @Html.DisplayFor(m => m.Name) // Iterate over subjects and questions for(int i = 0; i < Model.Subjects.Count; i++) { // Hidden field for subject identifier (if any) @Html.HiddenFor(m => m.Subjects[i].ID) // Display subject name @Html.DisplayFor(m => m.Subjects[i].Name) for (int j = 0; j < Model.Subjects[i].Questions.Count; j++) { // Hidden field for question identifier @Html.HiddenFor(m => m.Subjects[i].Questions[j].ID) // Display question text (with no binding) @Html.DisplayFor(m => m.Subjects[i].Questions[j].Text) foreach(var answer in Model.Subjects[i].Questions[j].PossibleAnswers ) { // Bind radio button to property on QuestionVM @Html.RadioButtonFor(m => m.Subjects[i].Questions[j].SelectedAnswer, answer.ID, new { id = answer.ID}) <label for="@answer.ID">@answer.Text</label> } } } // Submit button <input type="submit" value="save" /> }
Controller:
In the controller action that handles the form submission, you can access the submitted data through the StudentVM model.
[HttpPost] public ActionResult Edit(StudentVM model) { // Save and redirect (not shown) }
By using view models and the @Html.RadioButtonFor method, you can ensure that each question has a unique name attribute, which will allow radio buttons to be grouped correctly.
The above is the detailed content of How to Properly Group Radio Buttons by Question in ASP.NET MVC 5?. For more information, please follow other related articles on the PHP Chinese website!