本文介绍了在本地化的SelectList字符串枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我MVC3应用程序。我使用的选择列表来填充像这样枚举值组合框

In my MVC3 app. I'm using select list to populate combo box with enum values like this

<div class="editor-field">
   @Html.DropDownListFor(x => x.AdType, new SelectList(Enum.GetValues(typeof(MyDomain.Property.AdTypeEnum))), " ", new { @class = "dxeButtonEdit_Glass" })
</div>

MyDomain.Property看起来像这样

MyDomain.Property looks like this

 public enum AdTypeEnum
 {
     Sale = 1,
     Rent = 2,
     SaleOrRent = 3
 };

我如何用我的本地化的字符串进行本地化这些枚举?

How can I use my localized strings to localize these enums?

推荐答案

您可以编写一个自定义属性:

You could write a custom attribute:

public class LocalizedNameAttribute: Attribute
{
    private readonly Type _resourceType;
    private readonly string _resourceKey;

    public LocalizedNameAttribute(string resourceKey, Type resourceType)
    {
        _resourceType = resourceType;
        _resourceKey = resourceKey;
        DisplayName = (string)_resourceType
            .GetProperty(_resourceKey, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public)
            .GetValue(null, null);
    }

    public string DisplayName { get; private set; }
}

和一个自定义的 DropDownListForEnum 助手:

public static class DropDownListExtensions
{
    public static IHtmlString DropDownListForEnum<TModel, TProperty>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TProperty>> expression,
        string optionLabel,
        object htmlAttributes
    )
    {
        if (!typeof(TProperty).IsEnum)
        {
            throw new Exception("This helper can be used only with enum types");
        }

        var enumType = typeof(TProperty);
        var fields = enumType.GetFields(
            BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
        );
        var values = Enum.GetValues(enumType).OfType<TProperty>();
        var items =
            from value in values
            from field in fields
            let descriptionAttribute = field
                .GetCustomAttributes(
                    typeof(LocalizedNameAttribute), true
                )
                .OfType<LocalizedNameAttribute>()
                .FirstOrDefault()
            let displayName = (descriptionAttribute != null)
                ? descriptionAttribute.DisplayName
                : value.ToString()
            where value.ToString() == field.Name
            select new { Id = value, Name = displayName };

        var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var enumObj = metadata;
        var selectList = new SelectList(items, "Id", "Name", metadata.Model);
        return htmlHelper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
    }
}

和则很简单:

型号:

public enum AdTypeEnum
{
    [LocalizedName("Sale", typeof(Messages))]
    Sale = 1,
    [LocalizedName("Rent", typeof(Messages))]
    Rent = 2,
    [LocalizedName("SaleOrRent", typeof(Messages))]
    SaleOrRent = 3
}

public class MyViewModel
{
    public AdTypeEnum AdType { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            AdType = AdTypeEnum.SaleOrRent
        });
    }
}

查看:

@model MyViewModel

@Html.DropDownListForEnum(
    x => x.AdType,
    " ",
    new { @class = "foo" }
)

最后,你应该创建一个包含必需的密钥的 Messages.resx 文件(出售出租 SaleOrRent )。如果你想本地化你简单地定义一个 Messages.xx-XX.resx 与不同文化背景相同的密钥和交换当前线程的文化。

Finally you should create a Messages.resx file which will contain the necessary keys (Sale, Rent and SaleOrRent). And if you want to localize you simply define a Messages.xx-XX.resx with the same keys for a different culture and swap the current thread culture.

这篇关于在本地化的SelectList字符串枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:52