I have a list of checkboxes on a page, however, their values are not getting to the controller.
ListViewModel is where all my models I need in this view. Techniques is a list of Technique from database. Technique has TechiqueID and Type as attributes. tech is a bool array with the same size of techniques types
@model ListViewModel
@foreach (var item in Model.Techniques ){
<div>
@Html.CheckBoxFor(m => m.tech[item.TechniqueID])
@item.Type
</div>
}
Any idea why tech[] is null in the controller? It should be on the controller tech[0] = false, tech[1] = false and so on.
Output:
<div>
<input data-val="true" data-val-required="The Boolean field is required." id="tech_1_" name="tech[1]" type="checkbox" value="true" /><input name="tech[1]" type="hidden" value="false" />
Slippers, Distracting Tasks
</div>
<div>
<input data-val="true" data-val-required="The Boolean field is required." id="tech_2_" name="tech[2]" type="checkbox" value="true" /><input name="tech[2]" type="hidden" value="false" />
Hallway Placement
</div>
Your problem is that lists of controls need to be 0 based, and sequential. Your first item is based on 1.
If you need to keep this, then you will need to write a custom model binder for this. An easier solution might be to simply subtract one from the TechniqueID then add it back when you use it.
Another option would be to add a hidden field with a name of tech[0] and just ignore the first item in the list on post.