迄今为止我发现的最干净的解决方案是:http://www.codeproject.com/Tips/514321/A-Simple-and-Effective-Way-to-Localize-ASP-Net-MVC.
欢迎评论/反馈。
Edit 1:根据评论,我添加了代码示例并使用链接作为参考。
我创建了一个 customDataAnnotationsProvider 类:
public class CustomDataAnnotationsProvider: DataAnnotationsModelMetadataProvider
{
private ResourceManager resourceManager = new ResourceManager();
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName)
{
string key = string.Empty;
string localizedValue = string.Empty;
foreach (var attr in attributes)
{
if (attr != null)
{
if (attr is DisplayAttribute)
{
key = ((DisplayAttribute)attr).Name;
if (!string.IsNullOrEmpty(key))
{
localizedValue = resourceManager.GetLocalizedText(key);
((DisplayAttribute)attr).Name = localizedValue;
}
}
else if (attr is ValidationAttribute)
{
key = ((ValidationAttribute)attr).ErrorMessage;
if (!string.IsNullOrEmpty(key))
{
localizedValue = resourceManager.GetLocalizedText(key);
((ValidationAttribute)attr).ErrorMessage = localizedValue;
}
}
}
}
return base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
}
}
然后我在 Global.asax 中引用了 ApplicationStart 上的自定义提供程序
ModelMetadataProviders.Current = new Project.Web.Helpers.CustomDataAnnotationsProvider();
您不必更改模型并可以使用 Display 注释:
[Display(Name = "CustomerAccountNumber")]
public string CustomerAccountNumber { get; set; }