2

I have an enum type that is localized using DisplayAttribute, a resource file and aspnetcore built in localization support. I can successfully verify that the localization works in a view by for example using

Html.GetEnumSelectList<TypeExample>(). 

How can I get the same localized DisplayAttribute in a controller or even a Model.

I tried using code like:

var name = TypeExample.A.GetType()?
            .GetMember(TypeExample.A.ToString())?
            .FirstOrDefault()?
            .GetCustomAttribute<DisplayAttribute>()?.GetName();

but it does not return the localized display name.

I would like to use it in a model for an ApiController eg.

public class Model
{
    public TypeExample Type { get; set; }

    public string TypeDisplayValue => Type.GetDisplayValue()
}
2
  • You can use an attribute for this, I believe. stackoverflow.com/questions/33463166/… Commented May 22, 2019 at 8:59
  • I am using DisplayAttribute. Will try some of the solutions there later. However, first try did not work. Commented May 22, 2019 at 9:34

1 Answer 1

2

Finally I succeeded with this task.

I created a enum translator service that is registered i startup as transient service

public class EnumTranslatorService:IEnumTranslatorService
{
    private IModelMetadataProvider _metadataProvider;

    public EnumTranslatorService(IModelMetadataProvider metadataProvider)
    {
        _metadataProvider = metadataProvider;
    }

    public string TranslateDisplayName<TEnum>(TEnum e) where TEnum : struct
    {
        var a = _metadataProvider.GetMetadataForType(e.GetType());
        var name = a.EnumGroupedDisplayNamesAndValues.FirstOrDefault(t => 
                       t.Value ==  a.EnumNamesAndValues[e.ToString()]).Key.Name;

        return name ?? e.ToString();
    }
}

It uses IModelMetadataProvider that is created in aspnetcore. Once injected I use it as:

_enumTranslatorService.TranslateDisplayName(EnumExampleType.A)
Sign up to request clarification or add additional context in comments.

1 Comment

This was the only approach which allowed me to display the localized enum display name using the ShraredLocalizer approach with the dummy class and single resx file for every language.

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.