mvc3 - adding CSS class based on model attributes

2019-07-26 23:22发布

问题:

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

回答1:

In case you don't need to support the oldest browsers, you could also use the data-val-required html attribute which is already automatically added to the fields. In CSS this would be for example input[type="text"][data-val-required] { border-left: 2px solid blue; }.



回答2:

seems a bit manual.

and most importantly not working. The second argument of the EditorFor helper doesn't do what you think it does, contrary to the TextBoxFor helper. You could write a custom metadata provider which would allow you to decorate our view model property with a custom attribute and specify the class to apply on the editor template:

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


回答3:

I would suggest overriding creating an EditorTemplate: /Views/Shared/EditorTemplates/String.cshtml

Put this in the contents (sorry untested!):

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