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.
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.
@model User
@Html.PasswordFor(m => m.Password)
<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.
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.
@model User
@Html.Password("Password")
<input
id="Password"
name="Password"
type="password"
value="" />