w3resource

HtmlHelper - Password


In this tutorial, we will take a look at generating input type of passwords in the view of a ASP.NET MVC application.

To generate an input of type password (<input type="password">), HtmlHelper class provides us with two extension methods:

  • Password()
  • PasswordFor()

Using the following Activities model we will illustrate the use of the Password() and PasswordFor() method.

//Demo: Activity Model
public class Activity
{
    public int Id {get; set;}
    public string ActivityName {get; set;}
    public string Description {get; set;}
    public string Status {get; set;}
}

Password()

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

Password() method signature

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

Password() method can be overloaded just like every other methods.

//Demo: Html.Password() in Razor View
@model ActivityTab.Models.Activity
@Html.Password("OnlinePassword")
//Html Result:
<input 
        id="ActivityPassowrd" 
        name="ActivityPassowrd" 
        type="password" 
        value="" />

The above example will create password field for "ActivityPassowrd" property.

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">. Hence it automatically binds the value of the model property to password field.

PasswordFor() method signature

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

PasswordFor supports method overload just like other HtmlHelper methods

//Demo: PasswordFor() in Razor View
@model ActivityTab.Models.Activity
@Html.PasswordFor(m => m.Password)
//Html Result:
<input id="Password" name="Password" type="password" value=" password123" />

In the above code sample, the first parameter in PasswordFor() method is a lambda expression that specifies the model property to be bound to the password input box. We have specified Password property in the above example. So, it generates input password element with id and name set to property name. The value attribute will be set to the value of a Password property which is "password123" as illustrated in the above code snippet.



Inviting useful, relevant, well-written and unique guest posts