我有以下枚举:
public enum EventType : int
{
[Display(Description = "Downtime")]
Downtime = 0,
[Display(Description = "Speed")]
Speed = 1,
[Display(Description = "Quality")]
Quality = 2
}
我正在使用以下方式为其创建下拉列表:
@Html.EnumDropDownListFor(m => m.Type, "Event Type", new { @class = "form-control" })
我在下拉列表中获得的选项是:
为什么在地球上是Event Type
的选项?它可能代表什么样的价值?
[Display]
属性是我修复此问题的微弱尝试......
有什么想法吗?
答案 0 :(得分:1)
首先,您需要创建一个HTML Helper扩展程序,如:
public static class HtmlHelperExtensions
{
private static string GetDisplayName(this Enum enumeration)
{
var enumType = enumeration.GetType();
var enumName = Enum.GetName(enumType, enumeration);
var member = enumType.GetMember(enumName)[0];
var attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var attribute = (DisplayAttribute)attributes[0];
var displayName = attribute.Name;
if (attribute.ResourceType != null)
{
displayName = attribute.GetName();
}
return displayName;
}
public static MvcHtmlString EnumDropDownFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, Func<TEnum, bool> predicate=null, string optionLabel=null, object htmlAttributes=null) where TEnum : struct, IConvertible
{
var enumList = predicate == null ? Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
: Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(e => predicate(e));
var selectList = enumList
.Select(e => new SelectListItem
{
Value = Convert.ToUInt64(e).ToString(),
Text = ((Enum)(object)e).GetDisplayName(),
}).ToList();
if (!string.IsNullOrEmpty(optionLabel))
{
selectList.Insert(0, new SelectListItem
{
Text = optionLabel
});
}
return htmlAttributes==null
? htmlHelper.DropDownListFor(expression, selectList)
: htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
}
}
然后,如果你的Enum
喜欢吼叫
public enum EventType
{
[Display(Description = "Downtime")]
Downtime = 0,
[Display(Description = "Speed")]
Speed = 1,
[Display(Description = "Quality")]
Quality = 2
[Display(Description = "Test")]
Test = 3
}
并且您不想加载Test
,然后使用:
@Html.EnumDropDownFor(model => model.Type, types => types != EventType.Test, "Event Type", new {@class = "form-control"})
或者如果你需要加载所有:
@Html.EnumDropDownFor(model => model.Type, optionLabel:"Event Type", htmlAttributes:new {@class = "form-control"})