Complete Example of Html.Password and Html.PasswordFor – ASP.NET MVC 5

In this chapter, you will learn:
  1. What is Html.Password and Html.PasswordFor Helper Class?
  2. What is the difference between Html.Password and Html.PasswordFor method?
  3. Define Html.password class
  4. How to Validate PasswordFor field?
  5. How to send data from Password to Controller

What is Html.Password Helper Class?

Html.Password Helper class generates password input fields in a web form that is used to ask and validate user password. The characters entered in password field is masked with special character * (asterisk) or whatever you set on it.

Difference between Html.Password and Html.PasswordFor Helper Class

Html.Password and Html.PasswordFor both generates the password input field but still, they are different in nature. Html.Password is a basic type, loosely typed Helper class that is not bounded with the model property. Html.PasswordFor is a strongly typed class that is bounded by the model property. It is always advisable to use Html.PasswordFor class because it is secure, error-free, check errors on compile time and easy to use.

Define

Html.Password
Html.Password(string name, object value, object htmlAttributes)
Easy Example
@Html.Password("BasicPassword")


Html.PasswordFor
Html.PasswordFor(Expression<Func<dynamic,TProperty>> expression, object htmlAttributes)
Easy Example
@Html.PasswordFor(m => m.ConfirmPassword)

Complete Programming Example

Model: UserModel.cs
using System.ComponentModel.DataAnnotations;

namespace HtmlHelperDemo.Models
{
    public class UserModel
    {
        public int UserId { get; set; }
        public string UserName { get; set; }

        [Required(ErrorMessage ="Password is Required.")]
        public string Password { get; set; }

        [Required(ErrorMessage = "Confirmation Password is Required")]
        [Compare("Password", ErrorMessage = "Password Must Match")]
        public string ConfirmPassword { get; set; }
    }
}

View: Index.cshtml
@using HtmlHelperDemo.Models
@model UserModel

<h1>Html.PasswordFor Example</h1>

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    //Basic password Field Example
    @Html.Password("BasicPassword")
    <br />
    //Strongly Typed Hidden Field
    @Html.PasswordFor(m => m.Password)
    @Html.ValidationMessageFor(m=>m.Password, "", new { @class = "error"})
    <br />
    @Html.PasswordFor(m => m.ConfirmPassword)
    @Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { @class = "error" })
    <br /><br />
    <input id="Submit" type="submit" value="submit" />
}

<hr />

<p><strong>Value:</strong> @ViewBag.BasicPassword</p><br />
<p><strong>Value:</strong> @ViewBag.StrongPassword</p><br />

Controller: HomeController.cs
using System.Web.Mvc;
using HtmlHelperDemo.Models;

namespace HtmlHelperDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {            
             return View();
        }

        [HttpPost]
        public ActionResult Index(FormCollection fc, UserModel um)
        {
            if (ModelState.IsValid)
            {
                ViewBag.BasicPassword = fc["BasicPassword"];

                ViewBag.StrongPassword = um.ConfirmPassword;
                return View(um);
            }
            else
            {
                return View();
            }
        }
    }
}

Html Output
<form action="/" method="post"><input id="BasicPassword" name="BasicPassword" type="password" />    <br />
<input data-val="true" data-val-required="Password is Required." id="Password" name="Password" type="password" /><span class="field-validation-valid error" data-valmsg-for="Password" data-valmsg-replace="true"></span>    <br />
<input class="input-validation-error" data-val="true" data-val-equalto="Password Must Match" data-val-equalto-other="*.Password" data-val-required="Confirmation Password is Required" id="ConfirmPassword" name="ConfirmPassword" type="password" /><span class="field-validation-error error" data-valmsg-for="ConfirmPassword" data-valmsg-replace="true">Password Must Match</span>    <br /><br />
    <input id="Submit" type="submit" value="submit" />
</form> 

Summary

In this tutorial, you learned how to user Html.Password Helper class for generating Password input box in a web form. You also learned how to validate password field and send data back to the controller. In the next chapter, you will learn Html.Display Helper Class.

 

Share your thought