我想为我的ASP.NET MVC3网站编写一个帮助器,它将能够返回一个新的SelectList
,其中包含一个枚举的所有Description
属性标记在ASP.NET MVC3中使用显示标记填充DropDownListFor
例如,具有以下枚举:
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
我该如何修改thi s直接“合并”它直接在我的@Html.DropDownListFor
帮手?
我在互联网上看到过一些帮手,特别是here或here,但没有人为我工作。有没有人能够共享一个短和优雅帮手,它返回一个枚举成员的所有Display
属性,以便将它们放在一个DropDownListFor
?
我只是尝试你的答案,因为它是第一个。我在Tools \ Helpers \ AttributesHelperExtensions.cs中创建了两个方法,这是一个静态类,我写了一些帮助器。在我看来,'ToSelectList()'不能识别...有没有使用或我忘记的其他东西? – AlexB
对不起。您还需要在视图顶部指向扩展名的“@ using”指令。就像在C#代码中的其他任何地方一样,您必须让编译器知道在哪里找到该方法。 –