【发布时间】:2013-11-27 19:15:00
【问题描述】:
我正在尝试为我的 ASP.NET MVC3 网站编写一个帮助程序,它将能够返回一个新的 SelectList,其中包含一个枚举的所有 Description 属性标记
例如,使用以下枚举:
public enum Test
{
[Display(Name = "Membre 1")]
Member1,
[Display(Name = "Membre 2")]
Member2
}
我希望能够用类似的内容填写DropDownListFor:
@Html.DropDownListFor(m => m.MyTest, MyHelper(Test))
(MyTest 是 Test 变量)。
我希望我的DropDownList 包含:
我曾经使用过这个工作助手:
public static string GetEnumDescription(this Enum value)
{
Type enumType = value.GetType();
var enumValue = Enum.GetName(enumType, value);
MemberInfo member = enumType.GetMember(enumValue)[0];
var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var outString = ((DisplayAttribute)attrs[0]).Name;
if (((DisplayAttribute)attrs[0]).ResourceType != null)
{
outString = ((DisplayAttribute)attrs[0]).GetName();
}
return outString;
}
...但我无法在 SelectList 中使用它
如何修改它以直接将其“合并”到我的 @Html.DropDownListFor 助手中?
我在网上看到过一些帮手,尤其是here 或here,但没有人适合我。有没有人能够分享一个 short 和 elegant 帮助器,它返回 Enum 成员的所有 Display 属性,以便将它们放入 DropDownListFor 中?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-3 enums helper html.dropdownlistfor