I have an issues with Razor and MVC. I'm trying to create a Q and A. The question exists in a database, and the user can fill in an answer which they can then save.
My Interview Model is
public IEnumerable<InterviewQandA> QuestionsAndAnswers { get; set; }
public string LogoUrl { get; set; }
The QuestionsAndAnswers Model is
public string Question { get; set; }
public string Answer { get; set; }
public int Id { get; set; }
The controller returns the first of the 2 models.
The cshtml page is
@using (Html.BeginForm())
{
foreach (var qAndA in Model.QuestionsAndAnswers)
{
@Html.DisplayFor(a => qAndA.Question)<br />
@Html.TextBoxFor(a => qAndA.Answer)
@Html.HiddenFor(a => qAndA.Id)<br /><br />
}
<input type="submit" value="Save" />
}
The Interview model queries a database, and populates the Questions with Questions (string), the ID with the ID (int) and I hard code the Answer to an empty string (as there is no answer yet in the database).
The problem is, when I enter a value for the associated answer, it doesn't show in the Model in the post controller, which is
[HttpPost]
public ActionResult MyInterview(Interview model)
{
//model shows the questions etc but no value exists in the answer property
//do stuff
}
What am I doing wrong?
Edit
Using the following for loop has the same issue
for (int i = 0; i < Model.QuestionsAndAnswers.Count(); i++)
{
@Html.DisplayFor(a => Model.QuestionsAndAnswers.ElementAt(i).Question)<br />
@Html.TextBoxFor(a => Model.QuestionsAndAnswers.ElementAt(i).Answer)
@Html.HiddenFor(a => Model.QuestionsAndAnswers.ElementAt(i).Id)<br /><br />
}