ABP 自动本地化枚举

TagHelpers:select

  1. protected virtual List<SelectListItem> GetSelectItemsFromEnum(TagHelperContext context, TagHelperOutput output, ModelExplorer explorer)
  2. {
  3. var selectItems = new List<SelectListItem>();
  4. var isNullableType = Nullable.GetUnderlyingType(explorer.ModelType) != null;
  5. var enumType = explorer.ModelType;
  6. if (isNullableType)
  7. {
  8. enumType = Nullable.GetUnderlyingType(explorer.ModelType);
  9. selectItems.Add(new SelectListItem());
  10. }
  11. var containerLocalizer = _tagHelperLocalizer.GetLocalizerOrNull(explorer.Container.ModelType.Assembly);
  12. foreach (var enumValue in enumType.GetEnumValues())
  13. {
  14. var memberName = enumType.GetEnumName(enumValue);
  15. var localizedMemberName = AbpInternalLocalizationHelper.LocalizeWithFallback(
  16. new[]
  17. {
  18. containerLocalizer,
  19. _stringLocalizerFactory.CreateDefaultOrNull()
  20. },
  21. new[]
  22. {
  23. $"Enum:{enumType.Name}.{memberName}",
  24. $"{enumType.Name}.{memberName}",
  25. memberName
  26. },
  27. memberName
  28. );
  29. selectItems.Add(new SelectListItem
  30. {
  31. Value = enumValue.ToString(),
  32. Text = localizedMemberName
  33. });
  34. }
  35. return selectItems;
  36. }

框架代码:

  1. public static class EnumHelper
  2. {
  3. public static string GetLocalizedMemberName(Type enumType, object value, IStringLocalizerFactory stringLocalizerFactory)
  4. {
  5. var memberName = enumType.GetEnumName(value);
  6. var localizedMemberName = AbpInternalLocalizationHelper.LocalizeWithFallback(
  7. new[]
  8. {
  9. stringLocalizerFactory.CreateDefaultOrNull()
  10. },
  11. new[]
  12. {
  13. $"Enum:{enumType.Name}.{memberName}",
  14. $"{enumType.Name}.{memberName}",
  15. memberName
  16. },
  17. memberName
  18. );
  19. return localizedMemberName;
  20. }
  21. }

JSON文件格式:

  1. {
  2. "culture": "en",
  3. "texts": {
  4. "Enum:CarType.Sedan": "Sedan Car",
  5. "Enum:CarType.Hatchback": "Hatchback Car",
  6. "Enum:CarType.Coupe": "Coupe Car"
  7. }
  8. }