Home / ASP.NET - MVC / HtmlHelper - Password

HtmlHelper - Password

The HtmlHelper class has two extension methods to create ( with the specified name, value, and attributes html.Html.PasswordFor creates an element with the specified model attribute using a lambda expression.

Example Password() and PasswordFor():

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

Password()

The Html.Password() method creates a password part with name, value and html attributes.

Password() method syntax:

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

Password has many methods. Please visit MSDN for all Password.

Example Html.Password():

@model Student

@Html.Password("OnlinePassword")

HTML result:

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

Output in the browser


PasswordFor()

PasswordFor creates an element with the specified attribute using a lambda expression.

PasswordFor method syntax

MvcHtmlString Html.PasswordFor(Expression> expression, object htmlAttributes)

See more methods of PasswordFor.

Example: PasswordFor ()

@model Student

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

HTML result:

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

Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖