Search code examples
asp.net-mvcasp.net-mvc-3asp.net-mvc-4razorrazor-2

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


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


Solution

  • <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">