本地化枚举 [英] Enum localization
本文介绍了本地化枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你如何本地化枚举了 ListBoxFor
其中,多个选项是可能的?
How do you localize enums for a ListBoxFor
where multiple options are possible?
例如一个枚举
包含角色:
public enum RoleType
{
[Display(Description = "Administrator", ResourceType = typeof(Resource))]
Administrator = 1,
[Display(Description = "Moderator", ResourceType = typeof(Resource))]
Moderator = 2,
[Display(Description = "Webmaster", ResourceType = typeof(Resource))]
Webmaster = 3,
[Display(Description = "Guest", ResourceType = typeof(Resource))]
Guest = 4,
Etc.... = 5,
}
我已经看到了这与的DropDownList
/ selectlists
完成。但是,有没有办法为一个多选择列表中这样做呢?
I have seen this done with dropdownlist
/selectlists
. But is there a way to do this for a multi select list?
这是我想如何使用它,它是如何工作的,但现在并没有在不同的语言会转换:
This is how I'd like to use it, which is how it works now but doesn't get translated in a different language:
var roles = from role r in Enum.GetValues(typeof(RoleType))
select new
{
Id = (int)Enum.Parse(typeof(RoleType), r.ToString()),
Name = r.ToString()
};
searchModel.roles = new MultiSelectList(roles, "Id", "Name");
请注意:我有改名从角色枚举角色类型
Note: i have renamed the enum from Role to RoleType.
推荐答案
您可以实现一个描述属性。
You can implement a description attribute.
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
private readonly string _resourceKey;
private readonly ResourceManager _resource;
public LocalizedDescriptionAttribute(string resourceKey, Type resourceType)
{
_resource = new ResourceManager(resourceType);
_resourceKey = resourceKey;
}
public override string Description
{
get
{
string displayName = _resource.GetString(_resourceKey);
return string.IsNullOrEmpty(displayName)
? string.Format("[[{0}]]", _resourceKey)
: displayName;
}
}
}
public static class EnumExtensions
{
public static string GetDescription(this Enum enumValue)
{
FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return enumValue.ToString();
}
}
将其定义是这样的:
Define it like this:
public enum Roles
{
[LocalizedDescription("Administrator", typeof(Resource))]
Administrator,
...
}
和使用这样的:
var roles = from RoleType role in Enum.GetValues(typeof(RoleType))
select new
{
Id = (int)role,
Name = role.GetDescription()
};
searchModel.roles = new MultiSelectList(roles, "Id", "Name");
这篇关于本地化枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文