I have a basic ViewModel with a property that is a List of complex types. When binding, I seem to be stuck with getting either the list of values, OR the other model propert
Try to change the code for the Data collection to this, and let MVC take care of the naming:
<div class="editor-field">
@for (int i = 0; i < Model.Data.Count(); i++)
{
@Html.HiddenFor(m => m.Data[i].Id)
@Html.HiddenFor(m => m.Data[i].ParentId)
@Html.HiddenFor(m => m.Data[i].Name)
@Html.TextBoxFor(m => m.Data[i].Value)
}
</div>
Alternatively you could have created an EditorTemplate
for your nested ViewModel as follows.
@model MyDataItem
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.ParentId)
@Html.HiddenFor(model => model.Name)
@Html.TextBoxFor(model => model.Value)
Create a folder named 'EditorTemplates' in your 'Shared' folder and save the above as 'MyDataItem.cshtml'.
Then in your View, just call the following instead of the foreach
loop:
@Html.EditorFor(model => model.Data)
Feels a bit less hackier IMO :)
Just my 2 cents but something worth noting with this issue - the data member in the View Model must be defined as a public property for the postback model binding to work. I had a very similar problem to the above but used a public data member in my View Model. The same HTML is generated as shown above and all looks well but the model binder threw back an empty collection. Worth watching for...