set unchecked value of checkbox

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x