Binding each DropDownListFor within @foreach
With my ASP.NET WebForms experience, this is my first MVC project.
Here's a problem that I don't think the mechanism allows, but I could be
wrong.
Having a DropDownListFor within a @foreach is not that trivial.
First of all, the dropdown doesn't select the value I pass to it (m =>
question.Answer) -- notice in the image below they all show No Answer,
because it didn't select the correct value I loaded it with.
Secondly, since they all end up with the same form-field name, how could
the controller separate them back into the corresponding List<>?
I've been looking at this for an hour and searched for a similar example,
but I can't find any.
What's a good solution that's not a hard-coded hack or a workaround?
Model:
public List<SelectListItem> PossibleAnswers
{
get
{
return new List<SelectListItem>()
{
new SelectListItem() { Text = "No Answer", Value = "0" },
new SelectListItem() { Text = "Very Bad", Value = "1" },
new SelectListItem() { Text = "Bad", Value = "2" },
new SelectListItem() { Text = "Average", Value = "3" },
new SelectListItem() { Text = "Good", Value = "4" },
new SelectListItem() { Text = "Very Good", Value = "5" }
};
}
}
public enum SurveyAnswer
{
NoAnswer,
VeryBad,
Bad,
Average,
Good,
VeryGood
}
public class SurveyQuestionClass
{
public int ID { get; set; }
public string Question { get; set; }
public SurveyAnswer Answer { get; set; }
}
public List<SurveyQuestionClass> QuestionsAnswers { get; set; }
View:
@foreach (var question in Model.QuestionsAnswers)
{
<tr>
<td>
@Html.DropDownListFor(m => question.Answer,
Model.PossibleAnswers, new { style = "font-size: small;" })
</td>
<td>
@Html.Raw(question.Question)
</td>
</tr>
}
And it looks like this:
No comments:
Post a Comment