複数のオプションが可能な場合、列挙型をどのようにローカライズしますかListBoxFor
?
たとえば、enum
ロールを含む :
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
。しかし、複数選択リストでこれを行う方法はありますか?
[編集]
これは私が使いたい方法です。これは現在動作している方法ですが、別の言語に翻訳されていません。
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");
注: 列挙型の名前を Role から RoleType に変更しました。
ベストアンサー1
説明属性を実装できます。
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();
}
}
次のように定義します。
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");