多选列表的枚举本地化

时间:2013-06-26 19:40:22

标签: asp.net-mvc localization multi-select

我有enum个国家/地区:

public enum Country
    {
        [Display(Description ="Netherlands", ResourceType = typeof(MyResource))]
        Netherlands = 0,

        [Display(Description = "Germany", ResourceType = typeof(MyResource))]
        Germany = 1,

        [Display(Description = "Belgium", ResourceType = typeof(MyResource))]
        Belgium = 2,

        [Display(Description = "Luxembourg", ResourceType = typeof(MyResource))]
        Luxembourg = 3,

        [Display(Description = "France", ResourceType = typeof(MyResource))]
        France = 4,

        [Display(Description = "Spain", ResourceType = typeof(MyResource))]
        Spain = 5
    }

这是一种在MultiSelectList中显示枚举的扩展方法:

public static MvcHtmlString MultiSelectBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
        {
            return htmlHelper.ListBoxFor(expression, selectList, new { @class = "chzn-select", data_placeholder = Form.MultiSelect });
        }

MultiSelectList具有“已选择”的样式。有关详细信息,请参阅this网站

当我不需要它来支持更多语言等时,这一切都很好。

如何通过本地化实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以实现描述属性。

public class LocalizedDescriptionAttributre : DescriptionAttribute
{
     private readonly string _resourceKey;
    private readonly ResourceManager _resource;
    public LocalizedDescriptionAttributre(string resourceKey, Type resourceType)
    {
        _resource = new ResourceManager(resourceType);
        _resourceKey = resourceKey;
    }

    public override string Description
    {
        get
        {
            string displayName = _resource.GetString(_resourceKey);

            return string.IsNullOrEmpty(displayName)
                ? string.Format("[[{0}]]", _resourceKey)
                : displayName;
        }
    }
}

public static class EnumExtensions
{
    public static string GetDescription(this Enum enumValue) 
    {
        FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());

        DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute),
            false);

        if (attributes != null &&
            attributes.Length > 0)
            return attributes[0].Description;
        else
            return enumValue.ToString();
    }
}

像这样定义:

public enum Roles
{
    [LocalizedDescription("Administrator", typeof(Resource))]
    Administrator,
...
}

并像这样使用它:

var roles = from RoleType role in Enum.GetValues(typeof(RoleType))
                    select new
                    {
                        Id = (int)role,
                        Name = role.GetDescription()
                    };
 searchModel.roles = new MultiSelectList(roles, "Id", "Name");