You cannot use a foreach
loop to generate controls for a collection. The html you’re generating for each checkbox (and for the associated hidden input) is <input type="checkbox" name="item.ToExport" .../>
. Your model does not contain a property which is named item
.
Use a for
loop
@for(int i = 0; i < Model.ExportingGroups.Count; i++)
{
<tr>
<td class="js-export-checkbox">
@Html.CheckBoxFor(m => m.ExportingGroups[i].ToExport)
</td>
</tr>
}
Now your HTML will be
<input name="ExportingGroups[0].ToExport" .../>
<input name="ExportingGroups[1].ToExport" .../>
etc. which will correctly bind to your model
Edit
Alternatively you can use a custom EditorTemplate
for typeof GroupToExport
. Create a partial view /Views/Shared/EditorTemplates/GroupToExport.cshtml
@model yourAssembly.GroupToExport
<tr>
<td class="js-export-checkbox">
@Html.CheckBoxFor(m => m.ToExport)
</td>
</tr>
And then in the main view
@Html.EditorFor(m => m.ExportingGroups)
The EditorFor()
method will generate the correct html for each item in your collection based on the template.