Enum localization

后端 未结 15 814
慢半拍i
慢半拍i 2020-11-30 17:56

How do you localize enums for a ListBoxFor where multiple options are possible?

For example an enum that contains roles:

pu         


        
15条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 18:08

    I have used the accepted answer but changed it little bit. It is shorter and doesn't have custom class.

    This is my enum. All items have DisplayAttribute

    public enum OvertimeRequestedProvisionFor
    {
        [Display(ResourceType = typeof(Localization), Name = LocalizationKeys.General_Fee)]
        Fee = 1,
    
        [Display(ResourceType = typeof(Localization), Name = LocalizationKeys.General_Permit)]
        Permit = 2,
    }
    

    And this is the extension method

    public static string GetDisplayName(this Enum enumValue)
    {
        var fi = enumValue.GetType().GetField(enumValue.ToString());
    
        var attributes = (DisplayAttribute[])fi.GetCustomAttributes(typeof(DisplayAttribute), false);
    
        return attributes != null && attributes.Length > 0
                ? attributes[0].GetName()
                : enumValue.ToString();
    }
    

    Now all have to do:

    var localization = OvertimeRequestedProvisionFor.Fee.GetDisplayName();
    

提交回复
热议问题