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.


Author: Stuart

Crazy Person

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s