Html Password Helper in MVC3 Razor


  • Html.Password is the helper which renders a Textbox.
  • Helpers are not controls by itself, they simply generate html markup.
  • It renders a textbox which is different from basic textbox.
  • The textbox rendered using Password helper displays text entered inside it in password format i.e. bullets are displayed.


It has following four overloads :

Overload 1 :


This overload expects name, which is used to set name and id attribute.

Syntax :

<p>
     @Html.Password("Password")
</p>

UI :


Rendered HTML :

<p>
     <input id="Password" name="Password" type="password" />
</p>

The name parameter passed in the syntax, is used to set name and id attribute of the control. It renders input element with type = "Password".


Overload 2 :



This overload accepts two parameters. The name and value parameter. The value passed as value parameter is set to the value attribute.

Syntax :

<p>
     @Html.Password("Password","Password")
</p>

In the above syntax we are passing value as well. We are passing password as value.

UI :




Rendered HTML :



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

The value passes as the second parameter is used to set the value attribute of the control.


Overload 3 :




The third overload along with name and value parameter also accepts htmlAttributes object as parameter. 

Syntax :

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

UI :


We have set maxlength property to 10 using htmlAttributes object. We cannot enter characters more than 10 after setting this property.

Rendered HTML :

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

We can see in the above code that maxlength attribute is set to 10.



Overload 4 :




This attribute accepts three parameter, name value and Dictionary object containing one or more attributes to set.

Syntax :

<p>
     @Html.Password("Password","Password",dd)
</p>


We have defined the Dictionary object and passed as a parameter.

UI :


Rendered HTML :

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


We have passed two attributes in the Dictionary object i.e. maxlength and id attriute. Both are set in above code.


0 comments:

Post a Comment