Yesterday, I used checkbox helper in my MVC project and found some interesting things 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 Elements
CheckBox helper is different from the other controls because it will render two input elements. I have tried with the following code in a view.
And check this code in browser source view, it will render the following HTML.
<input id="chkAcceptPolicy" name="chkAcceptPolicy" type="checkbox" value="true"/>
<input name="chkAcceptPolicy" type="hidden" value="false"/>
I have probably wondered why the helper renders a hidden input in addition to checkbox input. After thinking over that, I have found reason for that is the HTML Specification indicates that a browser will submit a value for a checkbox only when checkbox is checked. So as per the 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 Elements
If we used model binding approach, then it will return value
true if value of checkbox is checked, otherwise return
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 found some interesting things. If you checked value of checkbox at that time, you will get the value of checkbox from the form collection object as "
Why it will contain both values because as per HTML Specifications, a browser will submit a value with comma separated when both elements have the same name.
chkAcceptPolicy checkbox value is checked and hidden element value is
false and due to this formcollection, returns value as ‘
The goal of this article is just to show you a unique thing about
@html.checkbox. Hope this will help you.