ASP.NET MVC Tutorials

Create Password field using HtmlHelper:

Learn how to generate Password field using HtmlHelper in razor view in this section.

HtmlHelper class includes two extension methods to generate a password field (<input type="password">) element in a razor view: Password() and PasswordFor().

We will use following Student model with Password() and PasswordFor() method.

Example: Student Model

public class Student
{
    public int StudentId { get; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; }
    public int Age { get; set; }
    public bool isNewlyEnrolled { get; set; }
    public string OnlinePassword { get; set; }
}

Password():

The Html.Password() method generates a input password element with specified name, value and html attributes.

Password() method signature:

MvcHtmlString Html.Password(string name, object value, object htmlAttributes)

Password() method has many overloads. Please visit MSDN to know all the overloads of Password() method.

Example: Html.Password() in Razor View

@model Student

@Html.Password("OnlinePassword")

Html Result:

<input 
    id="OnlinePassword" 
    name="OnlinePassword" 
    type="password" 
    value="" />

The above example will create password field for "OnlinePassword" property as shown below.

Output in the browser
Output of Password() or PasswordFor() method

PasswordFor():

PasswordFor helper method is a strongly typed extension method. It generates a <input type="password"> element for the model object property specified using a lambda expression. PasswordFor method binds a specified model object property to <input type="password">. So it automatically sets a value of the model property to password field and visa-versa.

PasswordFor() method signature:

MvcHtmlString Html.PasswordFor(Expression<Func<dynamic,TProperty>> expression, object htmlAttributes)

Visit MSDN to know all the overloads of PasswordFor() method.

Example: PasswordFor() in Razor View

@model Student

@Html.PasswordFor(m => m.Password)

Html Result:

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

In the above example, the first parameter in PasswordFor() method is a lambda expression that specifies the model property to be bind with the password textbox. We have specified Password property in the above example. So, it generates input password element with id & name set to property name. The value attribute will be set to the value of a Password property which is "mypassword" in the above example.

;