The @Html.CheckBox()
and @Html.CheckBoxFor()
helper methods generate 2 inputs, a checkbox and a hidden input
<input type="checkbox" name="yourPropertyName" .... value="true" >
<input type="hidden" name="yourPropertyName" value="false" >
This is by design because unchecked checkboxes to not post a value. If checked, then yourPropertyName=true&yourPropertyName=false
is submitted. The DefaultModelBinder
reads the first value (true
) and ignores the second (so the property is set to true
). If unchecked then just yourPropertyName=false
is submitted and the property is set to false
.
It hard to understand what you trying to achieve by creating 3 inputs with the same name, and the fact your claiming your getting 5 values means that your using FormCollection
to read the values (2 of the checkboxes are checked and one is not). You should NEVER use FormCollection
!
Use a view model and strongly typed html helpers to generate your views, and post back the model. For example
public class MyModel
{
public bool Property1 { get; set; }
public bool Property2 { get; set; }
....
}
and in the view
@model MyModel
....
@Html.CheckBoxFor(m => m.Property1)
@Html.CheckBoxFor(m => m.Property2)
....
Or if your wanting a collection of boolean
properties
public class MyModel
{
public List<bool> MyProperty { get; set; }
....
}
and in the view
for(int i = 0; i < Model.MyProperty.Count; i++)
{
@Html.CheckBoxFor(m => m.MyProperty[i])
}
Then in the controller
public ActionResult Edit(MyModel model)
{
// model will be correctly bound with the values of the boolean properties
}