I have nested foreach loops in my view, and am having problems with the radio buttons.
@foreach (var header in Model.surveyHeaders)
{
<h1>@header.Name</h1>
foreach (var subHeader in Model.surveySubHeaders.Where(x => x.SurveryHeaderID == header.ID))
{
<h2>@subHeader.Name</h2>
foreach (var question in Model.surveyQuestions.Where(x => x.SurveySubHeaderID == subHeader.ID))
{
@Html.RadioButtonFor(x => x.surveyResults.Where(y => y.SurveyQuestionID == question.ID).First().Value, 1);
@Html.RadioButtonFor(x => x.surveyResults.Where(y => y.SurveyQuestionID == question.ID).First().Value, 2);
@Html.RadioButtonFor(x => x.surveyResults.Where(y => y.SurveyQuestionID == question.ID).First().Value, 3);
@question.Question
}
}
}
The radio button name is always ‘Value’, so the radio buttons are not grouped. What can I do to achieve the grouping that is desired?
Ah collections in MVC, the joy! In order to make sure all fields are named accordingly in order to be correctly model bound on post, you need to use
forloops, that will set the indexes correctly.Before doing so, you’re going to have to tweak your model structure to save your headaches. You need to re-arrange your logic so that you have a hierarchical object model in which you can iterate more cleaner (this way we’re getting away from logic in the view too!)
Your survey header class, can’t you put a list of subheaders on it? Then your subheader class, can you put the list of questions for that subheader? That way you can do:
This assumes your new model structure is something like (with the following classes):
Also one other tip, for future reference, you use the following LINQ in your code:
You can simplify it because
Firstcan actually take a lamba, like so (although you should useFirstOrDefaultand null check it in future just for safety):