Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize the checkbox in a form into Json data

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?

like image 471
Blaise Avatar asked Nov 13 '22 23:11

Blaise


1 Answers

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).

like image 63
Jeremy Bell Avatar answered Nov 15 '22 13:11

Jeremy Bell