我的模型中有一个名为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>
发布于 2015-09-09 12:38:34
如果你使用的是MVC5.1或更高版本,有一种更简单、更清晰的方法:只需使用数据注释(来自System.ComponentModel.DataAnnotations
命名空间),如下所示:
public enum Color
{
[Display(Name = "Dark red")]
DarkRed,
[Display(Name = "Very dark red")]
VeryDarkRed,
[Display(Name = "Red or just black?")]
ReallyDarkRed
}
在视图中,只需将其放入适当的html helper中:
@Html.EnumDropDownListFor(model => model.Color)
发布于 2012-10-27 12:10:48
您可以使用Type.GetMember Method,然后使用反射使用get the attribute info:
// display attribute of "currentPromotion"
var type = typeof(UserPromotion);
var memberInfo = type.GetMember(currentPromotion.ToString());
var attributes = memberInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
var description = ((DisplayAttribute)attributes[0]).Name;
这里也有一些类似的帖子:
Getting attributes of Enum's value
How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?
发布于 2019-11-13 19:55:49
对于ASP.Net Core3.0,这对我很有效(归功于之前的回答者)。
我的枚举类:
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
public class Enums
{
public enum Duration
{
[Display(Name = "1 Hour")]
OneHour,
[Display(Name = "1 Day")]
OneDay
}
// Helper method to display the name of the enum values.
public static string GetDisplayName(Enum value)
{
return value.GetType()?
.GetMember(value.ToString())?.First()?
.GetCustomAttribute<DisplayAttribute>()?
.Name;
}
}
我的视图模型类:
public class MyViewModel
{
public Duration Duration { get; set; }
}
显示标签和下拉列表的剃刀视图示例。请注意,下拉列表不需要辅助方法:
@model IEnumerable<MyViewModel>
@foreach (var item in Model)
{
<label asp-for="@item.Duration">@Enums.GetDisplayName(item.Duration)</label>
<div class="form-group">
<label asp-for="@item.Duration" class="control-label">Select Duration</label>
<select asp-for="@item.Duration" class="form-control"
asp-items="Html.GetEnumSelectList<Enums.Duration>()">
</select>
</div>
}
https://stackoverflow.com/questions/13099834
复制