Waaghals
Waaghals

Reputation: 2609

How to add a Display attribute to an external enum?

I'm using enums for some properties which have only a certain number of options (e.g. Gender). I render these enums using @Html.EnumDropDownListFor(...) which uses the Display attribute to correctly render the options (these values come from a resource because they need to be translatable).

public enum Gender
{
    [Display(Name = "LabelMale", ResourceType = typeof(Translation))]
    Male,
    [Display(Name = "LabelFemale", ResourceType = typeof(Translation))]
    Female
}

But these enums come from an external project that cannot be edited or do not have access to the System.ComponentModel.DataAnnotations namespace. So I cannot add the required Display attributes to the values in these enum.

The viewmodels have the same problem, but for the viewmodels I can use the MetadataType(...) attribute.

However this does not work on enums.

Is there a similiar solution so I can have translatable enums?

Upvotes: 3

Views: 336

Answers (1)

BendEg
BendEg

Reputation: 21088

You can try to use TypeDesciptor to add an attribute at runtime. One problem could occure during reading those attributes from the asp.net-mvc framework, if they do not use TypeDescriptor for resolving those attributes.

But you could give it a try.

Upvotes: 1

Related Questions