How to serialize a checkbox in a form into Json data

We know that in MVC a CheckBoxForwill generate a checkboxc value="true"and a hiddenc value=false. Both input controls will have the same name.

This is very reasonable because the form will have the ability to POST a false value if the check box is not selected. And the connecting device will ignore hidden input when the checkbox returns true.

But now I have redefined the form submission event to send the form data to the WebAPI controller in JSON format.

When serializing form data, there is no mechanism for correctly analyzing the relationship between the checkbox and the hidden one. Therefore, when it is not installed, it returns a false, which is good. But when checking, it returns {true, false}instead true, because the function serializeArray()goes through each inputand finds two values ​​the same.

The question is: what is the best fix?

+5
source share
1 answer

My solution to this problem was to write my own HtmlHelper method, which displays the same input type = "checkbox" /> tag. Any other solution just seemed too hacked.

dotPeek .NET Reflector, , Microsoft HtmlHelper.CheckboxFor, .

2 , MVC , "bool" , ( "unchecked" ).

+1

All Articles