I have the following class
public class QuestionAnswerPair
{
public int QuestionID { get; set; }
public int AnswerID { get; set; }
public List<SelectListItem> Items { get; set; }
public string Key => "A" + QuestionID;
}
And in my View I have the following inside my View
var answerPair = @Model.SelectedAnswers.First(x => x.QuestionID == item.ID);
<input type="hidden" name="SelectedAnswers.Index" value="@answerPair.Key">
@Html.Hidden("SelectedAnswers[" + answerPair.Key + "].QuestionID", answerPair.QuestionID, new { id = "SelectedAnswers_" + answerPair.Key + "__QuestionID" })
@Html.Hidden("SelectedAnswers[" + answerPair.Key + "].AnswerID", answerPair.AnswerID, new { id = "SelectedAnswers_" + answerPair.Key + "__QuestionID" })
@Html.DropDownList("SelectedAnswers[" + answerPair.Key + "].AnswerID", answerPair.Items, new { @class = "form-control", id = "SelectedAnswers_" + answerPair.Key + "__QuestionID" });
To my View I pass a List of QuestionAnswerPair
and then I foreach through them and do the above piece of code, in the property Items
I have the answers that come from the database, but I also have one line that is always 0 with the text No Sellection as the default if AnswerID
is 0 but in the case where I have a value that is selected the DropDownList never Binds to that answer where if I had used DropDownListFor
it did Bind But when I post back the selected answer is null, with the above code the selected answer posts back to the server and I can use it
I pass through the following Model which contains SelectedAnswers
public class GroupViewModel
{
public List<InspectionQuestion> Questions { get; set; }
public List<QuestionAnswerPair> SelectedAnswers { get; set; }
public GroupViewModel(int groupId)
{
//DB Stuff to build SelectedAnswers
}
//For postback
public GroupViewModel()
{
}
}
EDIT:
The following is what I tried with EditorTemplate
@for (int index = 0; index < Model.SelectedAnswers.Count; index++)
{
var answer = Model.SelectedAnswers[index];
if (answer.QuestionID == item.ID)
{
@Html.EditorFor(x => answer, "SelectedAnswers")
}
}
Editor Template I have
@model InspectManagement.Models.QuestionAnswerPair
<td>
@Html.HiddenFor(x => x.QuestionID)
@Html.DropDownListFor(x => x.AnswerID, Model.Items, new {@class = "form-control"})
</td>
So my question is what is wrong with my View