Html CheckBoxFor helper in MVC3 Razor

  1. Html.CheckBoxFor is the helper used to render CheckBox in MVC3 Razor.
  2. Helpers are not controls by itself, they simply generate html markup.
  3. This helper helps in model binding. It binds the control with model's property.
This helper has following 3 overloads :

First Overload :


This overload accepts the linq expression. It binds the control with the model property.

Syntax :

<p>
     @Html.CheckBoxFor(c => c.IsMarried)
</p>

In the above syntax, we are biding the checkbox with IsMarried property of model.

UI :



Rendered HTML :



<p>
     <input id="IsMarried" name="IsMarried" type="checkbox" value="true" />
     <input name="IsMarried" type="hidden" value="false" />
</p>

We have binded the checkbox control with IsMarried attribute. The display name of this attribute is set as name and id attribute.


Overload 2 :




This overload accepts two parameters i.e. the expression and the htmlAttributes object.

Syntax :


<p>
     @Html.CheckBoxFor(c => c.IsMarried, new { id = "CheckBoxFor", @class = "checkbox" })
</p>

UI :



Rendered HTML :



<p>
     <input class="checkbox" id="CheckBoxFor" name="IsMarried" type="checkbox" value="true" /><input name="IsMarried" type="hidden" value="false" />
</p>

We can see that the htmlAttributes we have specified in the syntax has been set.



Overload 3 :




This is the third overload, which expects linq expression and htmlAttributes object.

Syntax :



<p>
     @Html.CheckBoxFor(c => c.IsMarried, dd)
</p>


In above syntax, we are passing Dictionary object of attributes. 


UI :


Rendered HTML :

<p>
     <input class="checkbox" id="CheckBoxFor" name="IsMarried" type="checkbox" value="true" />
     <input name="IsMarried" type="hidden" value="false" />
</p>

The class attribute and id attribute are set according to the object we passed in the syntax.


2 comments:

  1. this was the explanation i was looking for... i searched more than 50 sites and none has this kind of information... Nice job brother.. (o)

    ReplyDelete