Еще один вопрос о локализации MVC...
Я пытаюсь локализовать приложение ASP.Net MVC 3, используя локализованные файлы ресурсов, чтобы отображать тексты в представлениях, как рекомендовано.
Проблема, как обычно, заключается в попытке локализовать сообщения об ошибках по умолчанию из аннотаций данных.
Я знаю, что вы можете указать файл ресурсов и ключ в каждом атрибуте:
[Required(
ErrorMessageResourceType = typeof(CustomResourceManager),
ErrorMessageResourceName = "ResourceKey")]
public string Username { get; set; }
и даже, что лучше и предпочтительнее, вы можете переопределить сообщение по умолчанию, например: Ресурс по умолчанию для аннотаций данных в ASP.NET MVC, так что вы можете оставьте атрибуты как:
[Required]
public string Username { get; set; }
Этот последний подход - это тот, который я выполнял, и он работает, но только тогда, когда DataAnnotation, которую вы хотите переопределить, имеет сообщение ONE и ONLY ONE, поскольку оно всегда ищет ключ ресурса, называемый так же, как и атрибут в пользовательский файл ресурсов (например, "Обязательный" ) нуждается в записи "RequiredAttribute" в файле ресурсов)
Другие атрибуты, такие как StringLength, содержат более одного сообщения об ошибке, в зависимости от параметров, которые вы используете. Итак, если у вас есть модель, например:
public class Person
{
[Required]
[StringLengthLocalizedAttribute(10, MinimumLength = 5)]
[Display(Name = "User name")]
public string UserName { get; set; }
}
Сообщение об ошибке " Поле Имя пользователя должно быть строкой с минимальной длиной 5 и максимальной длиной 10."
И если вы измените атрибут StringLength на:
[StringLengthLocalizedAttribute(10)]
сообщение об ошибке изменяется на " Поле" Имя пользователя "должно быть строкой с максимальной длиной 10." Итак, в этом случае есть по крайней мере 2 сообщения об ошибках по умолчанию для переопределения и решения, выданные @kim-tranjan, терпят неудачу.
Мое частичное решение этого - реализовать собственный атрибут StringLength, например:
public class StringLengthLocalizedAttribute : StringLengthAttribute
{
public StringLengthLocalizedAttribute(int maximumLength) : base(maximumLength)
{
ErrorMessageResourceType = typeof(CustomValidationResource);
}
public override string FormatErrorMessage(string name)
{
ErrorMessageResourceName = MinimumLength > 0 ? "StringLengthAttributeMinMax" : "StringLengthAttributeMax";
return base.FormatErrorMessage(name);
}
}
Где у меня есть локализованный ресурс "CustomValidationResource" с сообщениями проверки, и установите его как ErrorMessageResourceType. Затем, переопределяя функцию FormatErrorMessage, я решаю, какая строка сообщения должна применяться в зависимости от дополнительных параметров.
Итак, вопрос здесь: Кто-нибудь знает, где мы можем найти весь список ключей ресурсов, используемых атрибутами DataAnnotation, и посмотреть, сколько разных сообщений об ошибках мы имеем в каждом, не тестируя каждый?
Или даже лучше, можем ли мы иметь исходный файл RESX, чтобы увидеть строковые шаблоны и локализовать их, используя те же ключи ресурсов? Таким образом, изменение только ErrorMessageResourceType должно работать для всех атрибутов DataAnnotations, и мне не нужно угадывать, где положить "{1}" или "{2}" в мою локализованную строку.
Спасибо, Серги