mvc3 - adding CSS class based on model attributes

喜欢而已 提交于 2020-01-05 10:11:24

问题


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


来源:https://stackoverflow.com/questions/6788231/mvc3-adding-css-class-based-on-model-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!