Friday, January 15, 2016

How to use the DisplayName attribute with Html.LabelFor in MVC 5.

Consider this Razor form in a .cshtml view:

<div>
   @using (Html.BeginForm("New", "User"))
   {
      <div>
         <h3>Sign up!</h3>
         <div>
            @Html.LabelFor(m => m.Username, new {@class = "MyLabel"})
            <br/>
            @Html.TextBoxFor(m => m.Username, new {@class = "MyInput"})
            @Html.ValidationMessageFor(m => m.Username)
         </div>
         <div>
            @Html.LabelFor(m => m.Password, new {@class = "MyLabel"})
            <br/>
            @Html.PasswordFor(m => m.Password, new { @class = "MyInput" })
            @Html.ValidationMessageFor(m => m.Password)
         </div>
         <div>
            @Html.LabelFor(m => m.PasswordConfirmation, new {@class = "MyLabel"})
            <br/>
            @Html.PasswordFor(m => m.PasswordConfirmation, new {@class =
                  "MyInput"})
            @Html.ValidationMessageFor(m => m.PasswordConfirmation)
         </div>
         <div>
            @Html.LabelFor(m => m.PhoneNumber, new { @class = "MyLabel" })
            <br />
            @Html.TextBoxFor(m => m.PhoneNumber, new { @class = "MyInput" })
            @Html.ValidationMessageFor(m => m.PhoneNumber)
         </div>
         <input type="submit" value="Register" class="MyButton" />
      </div>
   }
</div>

 
 

Alright, we probably don't want the labels for the password confirmation and the phone number to be "PasswordConfirmation" and "PhoneNumber" without spaces between the words right? What if we want to customize a label, and, perhaps, have the confirmation's label just be "Confirm" tersely? Well, we can do all that by decorating our model like so:

using System.ComponentModel;
namespace Whatever.Models
{
   public class Registration
   {
      public string Username { get; set; }
      
      public string Password { get; set; }
      
      [DisplayName("Confirm")]
      public string PasswordConfirmation { get; set; }
      
      [DisplayName("Phone Number")]
      public string PhoneNumber { get; set; }
   }
}

No comments:

Post a Comment