Friendly names in asp.net MVC5

·

2 min read

Last week I updated my project to ASP.net MVC 5 from MVC 4. The things I mention below may work with older MVC, it is just that I have not tried it out.

Using DataAnnotations in MVC 5 we can get the Drop Down list to display friendly names of an enum with is pretty cool. I hated the work around in the past where we had to give a function that returns the enum friendly names.

public enum PaymentType
{
    [Display(Name = "One Time")]
    OneTime,
    [Display(Name = "Monthly Recurring")]
    MonthlyRecurring
}

public class PaymentModel
{
    [StringLength(28, MinimumLength = 28)]
    [Display(Name = "Credit Card Number")]
    public string CreditCardNumber { get; set; }

    [StringLength(4, MinimumLength = 4)]
    [Display(Name = "Credit Card Expiry")]
    public string CreditCardExpiry { get; set; }

    [Display(Name = "Payment Type")]
    public PaymentType PaymentType { get; set; }

    [Display(Name = "Payment Due Date")]
    public DateTime PaymentDueDate { get; set; }
}

Now in the razor code I can write

<div class="form-group">
    @Html.LabelFor(m => m.PaymentType, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.EnumDropDownListFor(m => m.PaymentType, new { @class = "form-control" })
    </div>
</div>

and we get

paymentmodel.png