我可以通过以下方式本地化模型类属性:
public class Person
{
[Display(Name = ResourceKeys.Person_FirstName)]
[Required(Name = ResourceKeys.Person_FirstName_Required)]
public string FirstName { get; set; }
//...other properties
}
其中“ ResourceKeys”是特殊类,用于存储“伪”密钥并将它们与相关资源文件中的“适当”密钥链接:
public class ResourceKeys
{
public const string Person_FirstName = "FirstName"; // looks up for key "FirstName" in Person."culture".resx file
public const string Person_FirstName_Required = "FirstName_Required"; //dtto
//...
}
这很好用-例如@ Html.DisplayNameFor(model => model.FirstName)已正确本地化,并在德语中显示为“ Vorname”。
现在是问题所在。派生新类时,派生的属性未本地化:
public class Student : Person
{
//...
}
例如@ Html.DisplayNameFor(model => model.FirstName)可能根本没有本地化,而是呈现为“ FirstName”。似乎只在学生资源文件中搜索该密钥,而未找到该密钥本身。
我绝对想避免基类和派生类的资源文件中出现重复项。我该如何实现?
编辑:即使省略ResourceKeys类并且直接对注释字符串进行“硬编码”,派生属性的本地化也不起作用:
public class Person
{
[Display(Name = "FirstName")]
[Required(Name = "FirstName_Required")]
public string FirstName { get; set; }
//...other properties
}