List of objects not binding to the model on post back in asp.net mvc 4
You current implementation is rendering inputs that look like:
<input ... name="[0].Name" .../>
<input ... name="[1].Name" .../>
but in order to bind to to you model they would need to look like this:
<input ... name="SitePackges[0].LstPackageDisplayItems[0].Name" .../>
<input ... name="SitePackges[0].LstPackageDisplayItems[1].Name" .../>
<input ... name="SitePackges[1].LstPackageDisplayItems[0].Name" .../>
<input ... name="SitePackges[1].LstPackageDisplayItems[1].Name" .../>
A: You either need to render the controls in nested for
loops
for(int i = 0; i < Model.SitePackges.Count; i++)
{
@Html.HiddenFor(m => m.SitePackges[i].SiteId)
for(int j = 0; j < Model.SitePackges[i].LstPackageDisplayItems.Count; j++)
{
@Html.TextBoxFor(m => m.SitePackges[i].LstPackageDisplayItems[j].Name)
}
}
B: or use custom EditorTemplates
for your model types
Views/Shared/EditorTemplates/SitePackage.cshtml
@model SitePackage
@Html.HiddenFor(m => m.SiteId)
@Html.EditorFor(m => m.LstPackageDisplayItems)
Views/Shared/EditorTemplates/PackageDisplayItem.cshtml
@model PackageDisplayItem
@Html.TextBoxFor(m => m.Name)
and in the main view
@model SubscriptionModel
@using (@Html.BeginForm())
{
@Html.HiddenFor(m => m.MemberId)
@Html.EditorFor(m => m.SitePackges)
<input type="submit" />
}