The approach i found for internationalization of Enums or getting text of Enums from respective Resource files is to create an attribute class by inheriting DescriptionAttribute class
public class EnumResourceAttribute : DescriptionAttribute
{
public Type ResourceType { get; private set; }
public string ResourceName { get; private set; }
public int SortOrder { get; private set; }
public EnumResourceAttribute(Type ResourceType,
string ResourceName,
int SortOrder)
{
this.ResourceType = ResourceType;
this.ResourceName = ResourceName;
this.SortOrder = SortOrder;
}
}
Create another Static class that will provide extension methods for GetString and GetStrings.
public static class EnumHelper
{
public static string GetString(this Enum value)
{
EnumResourceAttribute ea =
(EnumResourceAttribute)value.GetType().GetField(value.ToString())
.GetCustomAttributes(typeof(EnumResourceAttribute), false)
.FirstOrDefault();
if (ea != null)
{
PropertyInfo pi = ea.ResourceType
.GetProperty(CommonConstants.ResourceManager);
if (pi != null)
{
ResourceManager rm = (ResourceManager)pi
.GetValue(null, null);
return rm.GetString(ea.ResourceName);
}
}
return string.Empty;
}
public static IList GetStrings(this Type enumType)
{
List<string> stringList = new List<string>();
FieldInfo[] fiArray = enumType.GetFields();
foreach (FieldInfo fi in fiArray)
{
EnumResourceAttribute ea =
(EnumResourceAttribute)fi
.GetCustomAttributes(typeof(EnumResourceAttribute), false)
.FirstOrDefault();
if (ea != null)
{
PropertyInfo pi = ea.ResourceType
.GetProperty(CommonConstants.ResourceManager);
if (pi != null)
{
ResourceManager rm = (ResourceManager)pi
.GetValue(null, null);
stringList.Add(rm.GetString(ea.ResourceName));
}
}
}
return stringList.ToList();
}
}
And on the elements of your Enum you can write :
public enum Priority
{
[EnumResourceAttribute(typeof(Resources.AdviceModule), Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberHigh, 1)]
High,
[EnumResourceAttribute(typeof(Resources.AdviceModule), Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberRoutine, 2)]
Routine
}
Where Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberHigh
&
Resources.ResourceNames.AdviceCreateAdviceExternaPriorityMemberRoutine
are constants in the resource file or you can say the strings whose values can be available in different cultures.
If you are implementing your web application in MVC architecture then create a property
private IList result;
public IList Result
{
get
{
result = typeof(Priority).GetStrings();
return result;
}
}
and in your .cshtml
file you can just bind the enum to your dropdownlist like :
@Html.DropDownListFor(model => Model.vwClinicalInfo.Priority, new SelectList(Model.Result))