Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

asp.net - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...