ASP MVC 3 - 使用LocalizationDisplayNameAttribute进行本地化

时间:2011-10-17 20:10:23

标签: asp.net-mvc-3 localization

有人可以告诉我在这段代码中我做错了什么:

    public class LocalizationDisplayNameAttribute : DisplayNameAttribute
    {


    public LocalizationDisplayNameAttribute(string resourceKey)
    {
        ResourceKey = resourceKey;
    }


    public override string DisplayName
    {
        get
        {
            string displayName = App_GlobalResources.Global.ResourceManager.GetString(ResourceKey);

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

    private string ResourceKey { get; set; }


}

文化被设定为cs。我有两个资源:Global.resx和Global.cs.resx,但是当我运行这个应用程序时,我总是从Global.resx获取字符串(它应该是Global.cs.resx)

1 个答案:

答案 0 :(得分:1)

以下对我来说很好:

public class LocalizationDisplayNameAttribute : DisplayNameAttribute
{
    public LocalizationDisplayNameAttribute(string resourceKey)
    {
        ResourceKey = resourceKey;
    }

    public override string DisplayName
    {
        get
        {
            string displayName = Global.ResourceManager.GetString(ResourceKey);
            return string.IsNullOrEmpty(displayName)
                ? string.Format("[[{0}]]", ResourceKey)
                : displayName;
        }
    }
    private string ResourceKey { get; set; }
}

查看型号:

public class MyViewModel
{
    [LocalizationDisplayName("foo")]
    public string Foo { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
}

查看:

@model MyViewModel
@Html.LabelFor(x => x.Foo)
@Html.EditorFor(x => x.Foo)

资源:

~/App_GlobalResources/Global.resx

foo: foo

~/App_GlobalResources/Global.cs.resx

foo: localized foo

~/web.config

<system.web>
    <globalization culture="cs" uiCulture="cs"/>
    ...
</system.web>

打印正确的本地化值。