如何在mvc3中对来自@ Html.LabelFor()的内容进行本地化

thi*_*mmk 7 asp.net localization razor asp.net-mvc-3

我只是稍微扩展了我的这个问题.

我在我的MVC Web应用程序中有我的App_LocalResources(我没有在单独的dll中).

我有一个不同组件的模型.在模型中我有2个类CountryCity:

public class Country: MyContainer
{
    public City city {get;set;}
} 

public class City
{
    public CityName {get;set;}
}

public class MyContainer
{
    public Cid {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

所以在我的action方法中,我创建并传递country的对象作为我的viewmodel.

在视图中我用这个:

@Html.LabelFor(mdl=>mdl.City.CityName)
@Html.LabelFor(mdl=>mdl.Cid)
Run Code Online (Sandbox Code Playgroud)

所以这很好用,带文字的标签用英文呈现.

但是如何修改它以便它从我的Web应用程序中的资源文件中读取文本?

Dar*_*rov 13

您可以编写自定义显示属性:

public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
    public LocalizedDisplayNameAttribute(string key): base(FormatMessage(key))
    {
    }

    private static string FormatMessage(string key)
    {
        // TODO: fetch the corresponding string from your resource file
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

public class City
{
    [LocalizedDisplayName("cityname")]
    public string CityName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您还可以查看以下本地化指南.它提供了样本属性的完整实现.


pip*_*omb 5

您可以使用[Display(ResourceType = typeof(App_LocalResources), Name = "AgreeTandCs")]where App_LocalResources是资源类的名称(your .resx),并且Name是您要引用的静态字符串的名称。在您的视图中照常使用LabelFor,它将自动提取您的资源。

在我的示例中,标签显示了以变量名AgreeTandCs存储的字符串,如果您以英语查看,它将在页面中显示为“我同意这些条款和条件”。