Mvc3 - adding a CSS class based on model attributes

I have a model element, for example:

[Required]
[Display(Name = "First name")]
[StringLength(50)]
public string FirstName { get; set; }

and I use the editor to pump it to the page like this:

@Html.EditorFor(x => x.FirstName )

I have many of these elements on the page and would like to add a CSS class to the input field called "Required" based on whether the model has the [Required] attribute.

Adding ...

@Html.EditorFor(x => x.FirstName, new { @class = "Required" }) )

... seems a little tame. Can I do it dynamically?

Thank you in advance

+1
source share
3 answers

If you do not need to support the oldest browsers, you can also use the data-val-requiredhtml attribute , which is already automatically added to the fields. In CSS, this will be, for example input[type="text"][data-val-required] { border-left: 2px solid blue; }.

+4

.

, , . EditorFor , , , , TextBoxFor. ,

[Required]
[Display(Name = "First name")]
[StringLength(50)]
[HtmlProperties(CssClass = "Required")]
public string FirstName { get; set; }
+6

I would suggest overriding the creation of EditorTemplate: /Views/Shared/EditorTemplates/String.cshtml

Put this in the contents (sorry unchecked!):

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { @class = "text-box single-line" + (ViewData.ModelMetadata.IsRequired ? " required" : "") })
0
source

All Articles