Giải pháp sạch nhất tôi đã tìm thấy cho đến nay là: http://www.codeproject.com/Tips/514321/A-Simple-and-Effective-Way-to-Localize-ASP-Net-MVC.
Nhận xét/phản hồi được hoan nghênh.
Chỉnh sửa 1: Dựa trên nhận xét, tôi đã thêm các ví dụ mã và sử dụng liên kết làm tham chiếu.
Tôi tạo ra một lớp 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);
}
}
Sau đó, tôi tham khảo các nhà cung cấp tùy chỉnh trên ApplicationStart trong Global.asax
ModelMetadataProviders.Current = new Project.Web.Helpers.CustomDataAnnotationsProvider();
Bạn không cần phải thay đổi mô hình của bạn và có thể sử dụng chú thích hiển thị :
[Display(Name = "CustomerAccountNumber")]
public string CustomerAccountNumber { get; set; }
bản sao có thể của [ASP.NET MVC 2 Localization/Globalizatio n được lưu trữ trong cơ sở dữ liệu?] (http://stackoverflow.com/questions/2568129/asp-net-mvc-2-localization-globalization-stored-in-the-database) – jrummell