【发布时间】:2012-10-17 11:32:41
【问题描述】:
我的模型中有一个名为Promotion 的属性,它的类型是一个名为UserPromotion 的标志枚举。我的枚举成员的显示属性设置如下:
[Flags]
public enum UserPromotion
{
None = 0x0,
[Display(Name = "Send Job Offers By Mail")]
SendJobOffersByMail = 0x1,
[Display(Name = "Send Job Offers By Sms")]
SendJobOffersBySms = 0x2,
[Display(Name = "Send Other Stuff By Sms")]
SendPromotionalBySms = 0x4,
[Display(Name = "Send Other Stuff By Mail")]
SendPromotionalByMail = 0x8
}
现在我希望能够在我的视图中创建一个 ul 来显示我的 Promotion 属性的选定值。这是我到目前为止所做的,但问题是我如何才能在此处获取显示名称?
<ul>
@foreach (int aPromotion in @Enum.GetValues(typeof(UserPromotion)))
{
var currentPromotion = (int)Model.JobSeeker.Promotion;
if ((currentPromotion & aPromotion) == aPromotion)
{
<li>Here I don't know how to get the display attribute of "currentPromotion".</li>
}
}
</ul>
【问题讨论】:
-
MVC5 确实支持枚举的 DisplayName 属性。
-
更清楚一点:只有
System.ComponentModel.DataAnnotations.DisplayAttribute。不是System.ComponentModel.DisplayNameAttribute。 -
这是否包括使用反射并因此影响性能?因为这将被称为很多时间。
-
@Nico 诀窍是将结果缓存在
static readonly字段中。这些值只需要从反射中读取一次。
标签: c# asp.net-mvc razor displayattribute