Yesterday, I have used checkbox helper in my mvc project and found some interesting thing when I saw render html of checkbox helper and access value of checkbox from form collection in controller action. I have described both the things below.
1. CheckBox helper renders 2 input element
CheckBox helper is different from the other controls because it will render two input elements. I have tried with following code in a view.
And check this code in browser source view it will render following html.
<input id="chkAcceptPolicy" name="chkAcceptPolicy" type="checkbox" value="true"/>
<input name="chkAcceptPolicy" type="hidden" value="false"/>
I have probably wondering why the helper renders a hidden input in addition to checkbox input. After thinking over that I have found reason for that the HTML Specification indicates that a browser will submit a value for a checkbox only when checkbox is checked. So as per above example that if
chkAcceptPolicy checkbox value is not checked then second input guarantees a value will appear.
2. Form Collection returns value of both input element
If we are used model binding approach then it will return value true if value of checkbox is checked otherwise return false.
But here, I have tried to access checkbox value from the Form Collection or Request Object.
public ActionResult Index(FormCollection fB)
ViewBag.ValueofCheckBox = fB["chkAccpetPolicy"];
Here I am found some interesting thing. If you are checked value of checkbox at that time you are getting value of checkbox from the form collection object as "
Why it will contains both value because as per HTML Specifications that a browser will submit a value with comma separated when both element have name same.
chkAcceptPolicy checkbox value is checked and hidden element value is false ndue to this formcollection return value a ‘true,false’.
The goal of this article just show you unique thing about @html.checkbox. Hope this will help you.