difference in input type=Checkbox, @HTML.CheckBox and @HTML.CheckBoxFor?

19,501

Solution 1

<Input type="Checkbox"> is Html markup for a checkbox and @Html.CheckBox & @HTML.CheckBoxFor are Html Helpers for Razor view engine..

suppose your viewmodel has a property Person.HadDinner, then usually for model binding to work properly you will have to name the checkbox Person.HadDinner and id as Person_HadDinner..

you can use @Html.CheckBox like

@HTML.CheckBox("Person.HadDinner", Model.Person.HadDinner)

but if you are using @HTML.CheckBoxFor, it will be strongly typed..

@HTML.CheckBoxFor(x => x.Person.HadDinner)

in both the cases, final output markup will be

<input type="checkbox" id="Person_HadDinner" name="Person.HadDinner">

Solution 2

The CheckboxFor (MSDN)

Returns a check box input element for each property in the object that is represented by an expression.

This means a checkbox element is created for each property in the expression provided. Where as Checkbox (MSDN)

Returns a check box input element by using the specified HTML helper and the name of the form field.

This creates a simple Checkbox element with the (optional) attributes provided.

Typically when referencing a property of an object (or the View Model) the most desired technique is to use CheckboxFor as the checkbox will be formatted correctly against your model.

Hope this helps.

EDIT: Response to OP Changes.

Both the CheckboxFor and Checkbox generate standard HTML output such as below.

@Html.CheckboxFor(m => m.SomeProperty)

<input type="checkbox" name="SomeProperty" id="SomeProperty" />

@Html.Checkbox("SomeProperty")

<input type="checkbox" name="SomeProperty" id="SomeProperty" />

The helper methods simply generate the HTML required to meet the expressions and attributes defined in the helpers.

Additionally, you dont have to use the helpers. You can write your HTML elements directly as needed.

Share:
19,501
Toubi
Author by

Toubi

Updated on June 17, 2022

Comments

  • Toubi
    Toubi almost 2 years

    I m new to MVC and confused what is difference in <Input type="Checkbox">, @HTML.CheckBox and @HTML.CheckBoxFor.

    Can you please guide why two helpers are provided for same thing ? In which situation which one should be used ?

    Thanks

    Edit: Added Input type=checkbox

  • Toubi
    Toubi over 10 years
    thanks. Can you please see my edit and tell about Input type=checkbox as well ? Thanks