We know that in MVC, a CheckBoxFor
will generate a checkbox
with a value="true"
and a hidden
with a value=false
. Both input controls will share the same name.
It is very reasonable because the form will be able to POST a false value if the box is unchecked. And the model binder will ignore the hidden input when the checkbox return a true.
But now i have overridden the form submit event in order to send the form data into a WebAPI controller in JSON format.
When serializing the form data, there is no mechanism to parse the relationship between the checkbox and the hidden correctly. Therefore, when unchecked, it returns a false
, which is okay. But when checked, it returns a {true, false}
instead of true
, because the serializeArray()
function goes through every input
and find two values goes to a same name.
The question is: What is the best way to correct it?
My solution to this problem was to write my own HtmlHelper method that renders a single <input type="checkbox" /> tag. Any other solution just seemed too hacky.
You can use dotPeek or .NET Reflector to look at how the Microsoft Team created the HtmlHelper.CheckboxFor method if you need any help accomplishing that task.
The 2 tag approach was taken to prevent MVC action parameters from throwing an exception when a "bool" parameter did not have a matching parameter sent to the controller (an unchecked checkbox doesn't send any value).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With