Create Checkbox in ASP.NET MVC
The HtmlHelper
class includes two extension methods to generate a <input type="checkbox">
HTML control in a razor view: CheckBox()
and CheckBoxFor()
.
We will use the following Student
model class throughout this article.
public class Student
{
public int StudentId { get; set; }
[Display(Name="Name")]
public string StudentName { get; set; }
public bool isActive { get; set; }
}
Html.CheckBoxFor()
The CheckBoxFor<TModel, TProperty>()
extension method generates <input type="checkbox">
control for the model property specified using a lambda expression.
Visit docs.microsoft.com to know all the overloads of CheckBoxFor() method.
@model Student
@Html.CheckBoxFor(m => m.isActive)
<input data-val="true"
data-val-required="The isActive field is required."
id="isActive"
name="isActive"
type="checkbox"
value="true" />
<input name="isActive" type="hidden" value="false" />
In the above example, the first parameter is a lambda expression that specifies the model property to bind with the checkbox element. We have specified isActive property in the above example.
Notice that it has generated an additional hidden field with the same name and value=false
.
When you submit a form with a checkbox, the value is posted only if a checkbox is checked. So, if you leave the checkbox unchecked, then nothing will be sent to the server.
Sometimes, you would want false
to be sent to the server. Because, an hidden input has the same name, it will send false
to the server if checkbox is unchecked.
Html.CheckBox()
The Html.CheckBox()
is a loosely typed method which generates a <input type="checkbox" >
with the specified name, isChecked
boolean, and HTML attributes.
@Html.CheckBox("isActive", true)
<input checked="checked"
id="isActive"
name="isActive"
type="checkbox"
value="true" />