Reputation: 11890
I need to present to the user a list of yes/no type questions. Here are my models:
class QuestionModel {
public String ID {get; set;}
public String Title {get; set; }
public bool Value {get; set; }
}
class QuestionsModel {
List<QuestionModel> Questions {get; set}
}
In my Razor code, I might be able to do something like:
@foreach(var item in Model.Questions) {
@Html.Label(item.Title);
@Html.RadioButton(item.ID, "Yes");
@Html.RadioButton(item.ID, "No");
}
However, I don't see how the Value field in QuestionModel will get populated based on what the user has selected. Please help. Regards.
Upvotes: 0
Views: 32
Reputation:
Firstly you need to use a for
loop or an EditorTemplate
for generating a collection otherwise the controls will not be named correctly and cannot be bound on post back
@model QuestionsModel
@(using Html.BeginForm())
{
for (int i = 0; i < Model.Questions.Count; i++)
{
string yes = i + "Yes";
string no = i + "No";
@Html.HiddenFor(m => m.Questions[i].ID)
@Html.DisplayFor(m => m.Questions[i].Title) // assuming you don't want to edit this
@Html.RadioButtonFor(m => m.Questions[i].Value, true, new { id = @yes })
<label for="@yes">Yes</label>
@Html.RadioButtonFor(m => m.Questions[i].Value, false, new { id = @no })
<label for="@no">No</label>
}
<input type="submit" value="Save" />
}
Upvotes: 1