1

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

3 Answers 3

6

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; }
Sign up to request clarification or add additional context in comments.

Comments

4

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; }.

1 Comment

That'll do for me. Thanks for all the comments!
0

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" : "") })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.