Is there a way of setting the default unchecked value of a checkbox? Am not using a databound control. This is passing data from a form and would like it to pass false as opposed to null when unchecked.
See Question&Answers more detail:osIs there a way of setting the default unchecked value of a checkbox? Am not using a databound control. This is passing data from a form and would like it to pass false as opposed to null when unchecked.
See Question&Answers more detail:osYes, using the default HtmlHelpers
will achieve this for you
<%: Html.Checkbox("myCheckbox") %>
or with Razor
@Html.Checkbox("myCheckbox")
The Checkbox()
method will render a input type="hidden"
field along side the input type="checkbox"
that will submit the value false
when the checkbox is unchecked.
<input id="myCheckbox" name="myCheckbox" type="checkbox" value="true" />
<input name="myCheckbox" type="hidden" value="false" />
If you want to submit a value other than false
then you should render the checkbox and hidden field yourself setting the value of the hidden field to your default value. Note that they must have the same name attribute.