1

I have an enum in my project like this:

 public enum Gender
 {
      [Display(Name="Gender.Male")]
      Male,

      [Display(Name="Gender.Female")]
      Female
 }

When I use the code below, it retrieves the name of Gender value from .resx files automatically and displays the translated value in razor view.

 @Html.DisplayFor(x => x.Gender) //result: Männlich

but, how to get localized names of Gender values in the backend? or how to use DisplayFor or something like that in controller class?

 //Desired
 string gender = DisplayFor(x => x.Gender); //gender = "Männlich"

Should I code a new method instead of using DisplayFor?

1 Answer 1

1

Get the name (or any other property) by code

// Example for a specifi value
string enumName = Gender.Male.GetType()
   .GetMember(Gender.Male.ToString())
   .SingleOrDefault()
   .GetCustomAttribute<DisplayAttribute>()
   .GetName();

Now that you have the name, get it from the Resx using the GetString(String, CultureInfo) for traditional .net, otherwise if you are using Localizer, then you can access it by the Item[String] property.

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

Comments

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.