I have researched all over the net but hopefully here someone can help me.
I have following ViewModel classes:
public class PersonEditViewModel
{
public Person Person { get; set; }
public List<DictionaryRootViewModel> Interests { get; set; }
}
public class DictionaryRootViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<DictionaryItemViewModel> Items;
public DictionaryRootViewModel()
{
Items = new List<DictionaryItemViewModel>();
}
}
public class DictionaryItemViewModel
{
public long Id { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
In the Edit view I use custom EditorTemplate to layout collection of Interests using @Html.EditorFor(m => m.Interests)
. There are two EditorTemplates that do the rendering:
DictionaryRootViewModel.cshtml:
@model Platforma.Models.DictionaryRootViewModel
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.Name)
@Html.EditorFor(model => model.Items)
DictionaryItemViewModel.cshtml:
@model Platforma.Models.DictionaryItemViewModel
@Html.HiddenFor(model => model.Id)
@Html.CheckBoxFor(model => model.Selected)
@Html.EditorFor(model => model.Name)
The problem:
When submitting the form using POST, only the Interests
collection gets populated and the Interest.Items
collection is always empty.
The request contains (among others) following field names, they are also present when inspecting Request.Forms data in the controller action method.
All contain proper values - but on the controller side, the object pvm in method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonEditViewModel pvm)
{
}
contains data in Interests collection (items with correct id and name), but for each element of the collection its' subcollection of Items is empty.
How do I make it to correctly pick the model?
As usual - the answer was in front of me the whole time. The DefaultModelBinder didn't pick up the Items values passed in request, because I "forgot" to mark Items collection as property - it was a field! The correct form taking into account helpful remark by @pjobs:
public List<DictionaryItemViewModel> Items
{get;set;}