How do you localize enums for a ListBoxFor
where multiple options are possible?
For example an enum
that contains roles:
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, }
I have seen this done with dropdownlist
/selectlists
. But is there a way to do this for a multi select list?
[EDIT]
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.
So what we usually do for enums that need to be localized is to write an extension class that provides a method to obtain the translated name. You can just use a switch that returns strings from the usual resources. That way, you provide translated strings for enums via the resources just like you do for other strings.
enums are not allocated in memory - they exist only on compilation stage. They only exist to tell compiler what value is Tuesday in ur example.
Normally, the name of an enum in c# can't contain any special characters or spaces.
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, ... }
And use it like this:
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With