3

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?

2
  • 3
    Did you think of defining your own enums and writing a class to do the conversion between yours and the external project? If there are a lot of them, reflection would come in handy too. Commented Sep 9, 2015 at 11:40
  • @Hamed Yes I've consider this, but I was hoping there is a better solution already in asp.net so I do not have to reinvent the wheel. Commented Sep 9, 2015 at 13:14

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

After initial testing it looked like EnumDropDownListFor() did not use the TypeConverter I've just confirmed this, the asp.net MVC 5.2.2 does not utilize the TypeDescriptor. It uses EnumHelper.GetDisplayName() which only read the Display attribute.(aspnetwebstack.codeplex.com/SourceControl/changeset/view/…)
Currently looking at github.com/nuhusky/gizmo-helpers/blob/master/Helpers/Html/… which does work when the TypeConverter is added to the enum, now looking to add it to the propery instead of the enum itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.