I have 2 model classes similar to:
class DependenciesModel{
List<int> DependencyComponentIDs { get; set; }
}
class ComponentModel{
int ComponentID { get; set; }
string Name { get; set; }
DependenciesModel Dependencies { get; set; }
}
The view uses looks something like this:
@model ComponentModel
@Html.HiddenFor(m => m.ComponentID)
<table>
<tr>
<td>@Html.LabelFor(m => m.Name)</td>
<td>@Html.TextBoxFor(m => m.Name)</td>
<td>@Html.ValidationMessageFor(m => m.Name)</td>
</tr>
<tr>
<td>Dependencies</td>
<td>@Html.EditorFor(m => m.Dependencies, "DependencyEdit")</td>
<td> </td>
</tr>
</table>
And an editor template DependencyEdit.cshtml in the EditorTemplates folder:
@model DependenciesModel
// There is more to this but I'm simplifying to get to the point
@Html.CheckBoxListFor(model => model.DependencyComponentIDs)
I see the values being posted back in Fiddler, but in the controller the Dependencies property is empty.
The interesting part is that the posted field values are just DependencyComponentIDs without any indication that they are part of the Dependencies property
I’ve split the dependency list into a separate Model because there’s a lot of management code in it that creates a good separation of concerns.
What do I need to do to get this working?
I had a similar issue with separating out address information into a separate class for better code management. in the end, I had to do a little more work to get it to return back and store in the object.
In your DependencyEdit.cshtml, try something like this
@model DependenciesModel
This isn’t a great solution, but it’s done the trick for me. You may want to also check out: How to create a CheckBoxListFor extension method in ASP.NET MVC?.