Using ASP.NET MVC 5, how do I get the localized DisplayAttribute for an Enum value in a View?

If I use value DisplayAttribute

by value Enum

, how do I get the localized resource value based on the value Enum

.

For example, if I have Enum

one defined like this:

public enum ExpireMode {
    [Display(ResourceType = typeof (ModelRes.ExpireMode), Name = "Never")]
    Never = 0,

    [Display(ResourceType = typeof (ModelRes.ExpireMode), Name = "ByCreated")]
    ByCreated = 1,

    [Display(ResourceType = typeof (ModelRes.ExpireMode), Name = "ByLastAccessed")]
    ByLastAccessed = 2,
}

      

And, suppose I created a file .resx

with a custom namespace ModelRes that contains the following:

enter image description here

How can I get the correct localized value if all I have is an enum value? I would like to use the correct localized value to display in the view.

I have looked at solutions that use type converters, extension methods, etc., but all seem to add a lot of code that should be relatively simple. Using it DisplayAttribute

for all other purposes makes localization pretty trivial as it handles it internally.

+3


source to share


1 answer


The easiest way to solve this problem, which does not require additional code, is the following code in the view itself:

@ModelRes.ExpireMode.ResourceManager.GetString(Model.ExpireMode.ToString())

      



Model.ExpireMode

is a property on the type model Enum

ExpireMode

. ModelRes

is its own namespace for the resource class ExpireMode

. I am taking ResourceManager

and calling GetString

with a string representation of the enum value, which gives me the correctly localized value.

0


source







All Articles