0

The following code

@Html.CheckBox("name", new { value = "valuename" })
@Html.CheckBox("name", new { value = "valuename2" })

I would expect to generate two checkboxes both with the same name but different values. When you submit them through a browser, they send the parameters "name:valuename" and "name:valuename2", allowing you to construct a list from the checkboxes.

And it does, half of the time. It also binds these parameters to a list no problem. But if you submit that form as a POST request and return the same view again then you get problems. This is because of InputExtensions:483 which is called by HtmlHelper.Checkbox. InputExtensions has a switch and if the inputType is of type InputType.CheckBox it will call GetModelStateValue to go through ModelState, find a parameter of the same name and then try and cast the value of that parameter to a boolean. So, because the value isn't "true" or "false" it fails.

This surprises me because I thought that this was a relatively common usecase for checkboxes- a group of checkboxes with the same name creating a list of different values, e.g "which of these products do you own?".

So my questions are, why does it work this way? And why is CheckBox checking the ModelState for it's value anyway, when I'd only expect that behaviour from CheckBoxFor? Is it a bug?

And given that ASP.NET MVC seems to assume the checkbox value will be "true" or "false"- is it or is it not HTML compliant to use values other than "true" and "false" with checkboxes?

Jansky
  • 1,455
  • 1
  • 17
  • 33
  • It's included in `CheckBox` because that's how the view resets all the values on your form after a POST (post-POST...). `CheckBoxFor` is just refactor-friendly syntax sugar for ``. If you don't want this, you can add this to your post action: `ModelState.Clear();` – freedomn-m Sep 19 '16 at 16:35
  • Its by design, and all the `HtmlHelper` methods check the value from `ModelState` first (see the 2nd part of [this answer](http://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) for an explanation). If you want a 'checkedlistbox' then create a view model with a `bool` property so that you get correct 2-way model binding (refer [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) for an example) –  Sep 19 '16 at 22:16

0 Answers0