Create Password field in ASP.Net MVC

The 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 User model with Password() and PasswordFor() method.

Example: User Model
public class User
{
    public int UserId { get; set; }
    public string Password { get; set; }
}

Html.PasswordFor()

The Html.PasswordFor<TModel,TProperty>() extension method is a strongly typed extension method. It generates a <input type="password"> element for the model object property specified using a lambda expression.

Visit docs.microsoft.com to know all the overloads of PasswordFor() method.

Example: PasswordFor() in Razor View
@model User

@Html.PasswordFor(m => m.Password)
Html Result:
<input id="Password" name="Password" type="password" value="" />

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 the Password property. It generates the following result.

password input field

Html.Password()

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

Visit docs.microsoft.com to know all the overloads of Password() method.

Example: Html.Password() in Razor View
@model User

@Html.Password("Password")
Html Result:
<input 
        id="Password" 
        name="Password" 
        type="password" 
        value="" />
Want to check how much you know ASP.NET MVC?