Adding style to [Required] fields in MVC with Razor

So you have a nice little model decorated with Attributes, and you’ve templated out your views but the users don’t know which fields are mandatory, the horror!

Here’s a model example:

public class PreQualificationModel
    [Display(Name = "Post code")]
    public string PostCode { get; set; }

    [Display(Name = "Number of employees")]
    public float NumEmployees { get; set; }

    [Display(Name = "Balance sheet (in GBP)")] 
    [DisplayFormat(DataFormatString = "{0:C}")]
    public decimal BalanceSheetGBP { get; set; }

    [Display(Name = "Sales turnover (in GBP)")]
    [DisplayFormat(DataFormatString = "{0:C}")]
    public decimal SalesTurnoverGBP { get; set; }


Usually you would have some indicator on the UI to show which fields are mandatory, a little red asterisk for example.  You could go through your view and add them manually but what happens when the model changes?  You have to do it all again, yuk.

but what if you could edit the EditorFor (and displayFor) templates to include it for you?  well you can, here is a simple example:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,

new { @class = "text-box single-line", type = "number" }) @if (ViewData.ModelMetadata.IsRequired) { <b style="color:Red;">*</b> }

Just create a folder called Editor Templates under Views/Shared in your solution and save this as String.cshtml and suddenly all string fields get red asterisks if they are mandatory.  you can do a similar thing for Decimal and other types as necessary.