I’ve got a model element like so:
[Required]
[Display(Name = "First name")]
[StringLength(50)]
public string FirstName { get; set; }
and I’m using an EditorFor to pump it out to the page like so:
@Html.EditorFor(x => x.FirstName )
I have many of these elements on a page and would like to add a CSS class to the input field called ‘Required’ based on whether or not the model has a [Required] attribute.
Adding…
@Html.EditorFor(x => x.FirstName, new { @class = "Required" }) )
…seems a bit manual. Is there a way I can do this dynamically?
Thanks in advance
In case you don’t need to support the oldest browsers, you could also use the
data-val-requiredhtml attribute which is already automatically added to the fields. In CSS this would be for exampleinput[type="text"][data-val-required] { border-left: 2px solid blue; }.