TextBoxFor Helper in MVC3 Razor

  1. Html.TextBoxFor is the helper which renders a TextBox.
  2. Helpers are not controls by itself, they simply generate html markup.
  3. Html.TextBoxFor binds the control to the model.
  4. It accepts linq expression which helps in model binding.
It has following overloads :

Overload 1 :


This overload accepts a linq expression, which binds the property to the model.

Syntax :

<p>
     @Html.TextBoxFor(c => c.Password)
</p>

UI :



Rendered HTML :

<p>
   <input id="Password" name="Password" type="text" value="" />
</p>


Overload 2 :



This overload accepts two parameters, linq expressiona and htmlAttributes object.

Syntax :

<p>
     @Html.TextBoxFor(c => c.Password, new { maxlength = "10"})
</p>

UI :



Rendered HTML :

<p>
   <input id="Password" maxlength="10" name="Password" type="text" value="" />
</p>

The maxlength attribute is set to 10 as passed by htmlAttributes object.


Overload 3 :




This overload is similar to previous one, just that it accepts IDictionary object of htmlAttributes.

Syntax :

<p>
     @Html.TextBoxFor(c => c.Password,textBox)
</p>


We have created a Dictionary of attributes and passed as parameter.


UI :



Rendered HTML :

<p>
   <input id="Password" maxlength="10" name="Password" style="color:Red" type="text" value="" />
</p>

0 comments:

Post a Comment