Reputation: 87
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.
Upvotes: 0
Views: 9838
Reputation: 10115
I did it using Razor , works for me
Getting Value
bool CashOnDelivery = Product.CashOnDelivery == null ? false : Convert.ToBoolean(Product.CashOnDelivery);
Razor View
@Html.CheckBox("CashOnDelivery", CashOnDelivery) (Not nullable bit)
Razor don't support nullable bool
In C# side
Insert.CashOnDelivery = Convert.ToBoolean(Collection["CashOnDelivery"].Contains("true")?true:false);
Upvotes: 0
Reputation: 24522
Yes, 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.
Upvotes: 5
Reputation: 43074
This can be achieved by adding an additional control to the form thus:
<input type="hidden" name="checkbox1" value="off">
<input type="checkbox" name="checkbox1" value="on"> My checkbox
That way you have a default value for your checkbox should it not be checked. If it is checked then the checkbox overrides the hidden field, for this to work the checkbox and the hidden field must have the same name.
Upvotes: 0