CheckBoxFor(t => t.boolValue, new { disabled=”disabled” }) method to render a checkbox, in disabled mode.
The method renders a hidden field as well.
My question is why does this hidden field has a false value for disabled check box?
I believe the purpose of the hidden field is to have some extra behavior over the default check box behavior
Is there a way to override default MVC functionality so that the value of this hidden field
is based on the state of the checkbox even in disabled mode?
The hidden field is used to bind the checkbox value to a boolean property. The thing is that if a checkbox is not checked, nothing is sent to the server, so ASP.NET MVC uses this hidden field to send false and bind to the corresponding boolean field. You cannot modify this behavior other than writing a custom helper.
This being said, instead of using
disabled="disabled"usereadonly="readonly"on the checkbox. This way you will keep the same desired behavior that the user cannot modify its value but in addition to that its value will be sent to the server when the form is submitted:UPDATE:
As pointed out in the comments section the
readonlyattribute doesn’t work with Google Chrome. Another possibility is to use yet another hidden field and disable the checkbox:UPDATE 2:
Here’s a full testcase with the additional hidden field.
Model:
Controller:
View:
When the form is submitted the value of the Foo property is
true. I have tested with all major browsers (Chrome, FF, IE).