Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying friendly, localized enum values using DataAnnotations in ASP.NET MVC2

What's the recommended way to display localized enum properties in MVC2?

If I have a model like this:

public class MyModel {
  public MyEnum MyEnumValue { get; set; } 
}

and a line in the view like this:

<%: Html.DisplayFor(model => model.MyEnumValue) %>

I was hoping to just annotate the enum values with DisplayAttribute like this:

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
}

That's not supported. It seems there's something else needed. What's the nicest way to implement it?

like image 901
Tim Rogers Avatar asked Aug 19 '10 12:08

Tim Rogers


1 Answers

You can try using the DescriptionAttribute for this.

E.g.

In the view model:

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;
        }

In the view:

Model.GetDescription(Model.myEnum.GetType(), Model.myEnum) to retrieve the value set in Description. 

I am using something similar to set the displayname and value in my Html.Dropdown.

like image 69
SO User Avatar answered Sep 23 '22 11:09

SO User