0

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 />
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • You will need to use for loop instead of foreach, and use array index in the name property of each control. You may google something like how to bind and post collection in MVC razor view, and you will get number of related articles. As I am commenting from phone, i am having limited options here. – Nirman Mar 16 '18 at 19:34

1 Answers1

2

Try this

@Html.Label(Model.QuestionsAndAnswers[i].Answer, Model.QuestionsAndAnswers[i].Question)

to post the information back you need to change the way you are iterating through your list

@for (int i = 0; i < Model.QuestionsAndAnswers.Count; i++) { 
    @Html.Label(Model.QuestionsAndAnswers[i].Answer, Model.QuestionsAndAnswers[i].Question)<br />
    @Html.TextBoxFor(model => Model.QuestionsAndAnswers[i].Answer)
    @Html.HiddenFor(a => .QuestionsAndAnswers[i].Id)<br /><br />
}
Fran
  • 6,440
  • 1
  • 23
  • 35