MVC3 - 基于模型的属性添加CSS类 [英] mvc3 - adding CSS class based on model attributes

查看:121
本文介绍了MVC3 - 基于模型的属性添加CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型元素,像这样:

I've got a model element like so:

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

和我使用的是EditorFor泵出来的页面,像这样:

and I'm using an EditorFor to pump it out to the page like so:

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

我有很多页面上的这些元素,并想一个CSS类添加到基于模型是否有一个[必需]属性的输入域称为必要。

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.

添加...

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

...似乎有点手册。有没有一种方法,我可以做到这一点动态?

...seems a bit manual. Is there a way I can do this dynamically?

在此先感谢

推荐答案

在情况下,你不需要支持的最古老的浏览器,你也可以使用数据-VAL-要求 HTML属性这已经自动添加到字段。在CSS中,这将是例如输入[类型=文本] [数据-VAL-必需] {左边框:2px的固体蓝色; }

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

这篇关于MVC3 - 基于模型的属性添加CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆