在MVC2中显示本地化枚举属性的推荐方法是什么?
如果我有这样的模型:
public class MyModel { public MyEnum MyEnumValue { get; set; } }
并在视图中的一行如下:
<%: Html.DisplayFor(model => model.MyEnumValue) %>
我希望通过DisplayAttribute注释枚举值,如下所示:
public enum MyEnum { [Display(Name="EnumValue1_Name",ResourceType=typeof(Resources.MyEnumResources))] EnumValue1,[Display(Name="EnumValue2_Name",ResourceType=typeof(Resources.MyEnumResources))] EnumValue2,[Display(Name="EnumValue3_Name",ResourceType=typeof(Resources.MyEnumResources))] EnumValue3 }
不支持似乎还有其他需要的东西。实施它最好的方法是什么?
解决方法
您可以尝试使用DescriptionAttribute。
例如。
在视图模型中:
public enum MyEnum { [Description("User Is Sleeping")] Asleep,[Description("User Is Awake")] Awake } public string GetDescription(Type type,string value) { return ((DescriptionAttribute)(type.GetMember(value)[0].GetCustomAttributes(typeof(DescriptionAttribute),false)[0])).Description; }
在视图中:
Model.GetDescription(Model.myEnum.GetType(),Model.myEnum) to retrieve the value set in Description.
我使用类似的东西来设置我的Html.Dropdown中的displayname和值。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。