Am trying to get a very simple, console app to work with localizing and TryValidateObject on my object.
I have a Student class:
public class Student
{
[Display(ResourceType = typeof(Strings), Name = @"Student_Name_DisplayName")]
[Required]
public string Name {get; set;}
}
I have a public resource Strings.resx for my default language (English) with
Key = Student_Name_DisplayName
Value = Name
I have an internal resource file Strings.es.resx for Spanish
Key = Student_Name_DisplayName
Value = Nombre
If I create a new Student object and do not set the Name property to something, I expect to see an error if I call Validator.TryValidateObject. I do.
Setting the current Culture and UI Culture to English, I get the validation error: "The Name field is required."
Setting the current Culture and UI culture to Spanish, I get the validation error: "The Nombre field is required."
Pretty close, but I'd like the rest of the message to be in Spanish as well.
I've found that doing this in Silverlight works - Silveright somehow "sees" the right language and gets me the right error. However, I have some server-side processing I'd also like to have return the proper translated string.
The full code is below:
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
Student student = new Student();
var validationResults = new Collection<ValidationResult>();
Validator.TryValidateObject(student, new ValidationContext(student, null, null), validationResults, true);
if (validationResults.Count > 0)
Debug.WriteLine(validationResults[0].ErrorMessage);
//produces "The Name field is required"
validationResults.Clear();
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("es");
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es");
Student student2 = new Student();
Validator.TryValidateObject(student2, new ValidationContext(student2, null, null), validationResults, true);
if (validationResults.Count > 0)
Debug.WriteLine(validationResults[0].ErrorMessage);
//produces "The Nombre field is required"
Thoughts?
Thanks (Gracias)