在 MVC 中显示枚举下拉列表的自定义文本
Display a custom text for enum dropdown list in MVC
我无法显示 enum
的自定义文本。当我尝试显示时,我得到 Slot1、Slot2 等
如何获取自定义文本?
public enum TimeSlots
{
[Display(Name =@"11:00AM - 12:00PM")]
Slot1,
[Display(Name = @"12:00PM - 10:00PM")]
Slot2,
[Display(Name =@"01:00PM - 02:00PM")]
Slot3,
[Display(Name = "02:00PM - 03:00PM")]
Slot4,
[Display(Name = "03:00PM - 04:00PM")]
Slot5,
[Display(Name = "04:00PM - 05:00PM")]
Slot6
}
以下是 DropDownList
的代码:
<label asp-for="TimeSlot"></label>
@Html.DropDownListFor(m => m.TimeSlot,
new SelectList(Enum.GetValues(typeof(TimeSlots))),"Select TimeSlot",new { @class = "form-control" })
尝试以下操作:
@Html.DropDownList("enumlist1", Enum.GetValues(typeof(TimeSlots))
.Cast<TimeSlots>()
.Select(e => new SelectListItem() { Value = e.ToString(), Text = e.GetDisplayName() }))
上面的代码使用了following extension method:
public static class EnumExtensions
{
public static string GetDisplayName(this Enum value)
{
return value.GetType()
.GetMember(value.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
?.GetName();
}
}
创建的下拉列表如下所示:
我无法显示 enum
的自定义文本。当我尝试显示时,我得到 Slot1、Slot2 等
如何获取自定义文本?
public enum TimeSlots
{
[Display(Name =@"11:00AM - 12:00PM")]
Slot1,
[Display(Name = @"12:00PM - 10:00PM")]
Slot2,
[Display(Name =@"01:00PM - 02:00PM")]
Slot3,
[Display(Name = "02:00PM - 03:00PM")]
Slot4,
[Display(Name = "03:00PM - 04:00PM")]
Slot5,
[Display(Name = "04:00PM - 05:00PM")]
Slot6
}
以下是 DropDownList
的代码:
<label asp-for="TimeSlot"></label>
@Html.DropDownListFor(m => m.TimeSlot,
new SelectList(Enum.GetValues(typeof(TimeSlots))),"Select TimeSlot",new { @class = "form-control" })
尝试以下操作:
@Html.DropDownList("enumlist1", Enum.GetValues(typeof(TimeSlots))
.Cast<TimeSlots>()
.Select(e => new SelectListItem() { Value = e.ToString(), Text = e.GetDisplayName() }))
上面的代码使用了following extension method:
public static class EnumExtensions
{
public static string GetDisplayName(this Enum value)
{
return value.GetType()
.GetMember(value.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
?.GetName();
}
}
创建的下拉列表如下所示: