Explain to me the all possible ways how we can generate checkbox control using HtmlHelper in razor view with an example.
How we generate checkbox control using HtmlHelper in razor view?
496317-Feb-2020
Updated on 17-Feb-2020
Home / DeveloperSection / Forums / How we generate checkbox control using HtmlHelper in razor view?
Explain to me the all possible ways how we can generate checkbox control using HtmlHelper in razor view with an example.
Nishi Tiwari
17-Feb-2020The checkbox in HtmlHelper class includes two extension methods to generate a <input type="checkbox"> element in razor view that is CheckBox() and CheckBoxFor().
Now we will use the following Student model with CheckBox() and CheckBoxFor() method.
Example of Student Model
CheckBox()
This Html.CheckBox() is defined as a loosely typed method that generates a <input type="checkbox" > with the specified name, isChecked boolean and also with the html attributes.
CheckBox() method Signature
Example of Html.CheckBox() in Razor View
@Html.CheckBox("isNewlyEnrolled", true)
Html Result:
In the above-given example, the first parameter is "isNewlyEnrolled" property of the Student model class which will be set as a name & id of the textbox and the second parameter is the boolean value, which either checks or unchecks the checkbox.
CheckBoxFor
The CheckBoxFor helper method is defined as a strongly typed extension method that generates <input type="checkbox"> element for the model property specified using a lambda expression. This method binds a specified model object property to the checkbox element so it automatically checked or unchecked a checkbox based on the property value.
CheckBoxFor() method Signature:-
Example of Html.CheckBoxFor() in Razor View
The given above example, the first parameter in CheckBoxFor() method is a lambda expression that specifies the model property to be bound with the checkbox element and we have specified isNewlyEnrolled property in the above example. So, it generates <input type="checkbox"> element with id & name set to property name – isNewlyEnrolled and also the value attribute will be set to the value of isNewlyEnrolled boolean property.
The above Html result, we noticed that it has generated additional hidden field with the same name and value=false and this is because when we submit a form with a checkbox, the value is only posted if the checkbox is checked and if we leave the checkbox unchecked then nothing will be sent to the server when in many situations we want false to be sent instead. But as the hidden input has the same name as the checkbox, then if the checkbox is unchecked we will still get a 'false' sent to the server.