My code:
public ActionResult Index()
{
IndexViewModel indexViewModel = new IndexViewModel();
indexViewModel.Questions = GetQuestions();
//Look here, I need to associate a answer for each question, i make a array with the number of questions, this seems a good idea?
indexViewModel.Answers = new Answer[indexViewModel.Questions.Count];
return View(indexViewModel);
}
[HttpPost]
public ActionResult Index(IndexViewModel indexViewModel)
{
if (ModelState.IsValid)
{
//The problem is here:
//The **Questions** property in IndexViewModel comes empty
//and I need to associate Questions and Answers
...
context.SaveChanges();
return RedirectToAction("Index");
} else
{
indexViewModel.Questions = GetQuestions();
indexViewModel.Answers = new Answer[indexViewModel.Questions.Count];
return View(indexViewModel);
}
}
private IList<Question> GetQuestions()
{
return context.Question.ToList();
}
The problem is in code comments. Thanks.
Update:
My HTML:
@using (Html.BeginForm()) {
<fieldset>
@Html.ValidationSummary(false, "Fix the erros:")
@for (int i = 0; i < Model.Questions.Count; i++)
{
<div class="editor-label">
@Html.DisplayFor(model => model.Questions[i].Description)
</div>
<div class="editor-field">
@Html.LabelFor(model => model.Answers[i].Score)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Answers[i].Score)
</div>
}
<p>
<input type="submit" value="Send" />
</p>
</fieldset>
}
probably the format you are rendering the view is not compliant to the default binder:
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
If you can’t change the format of the HTML you have to create your own custom binder
ASP.NET MVC – Custom model binder able to process arrays