2013-09-05 35 views
2

我正試圖獲得一個非常簡單的控制檯應用程序,以便在本地對象上使用本地化和TryValidateObject。C#/ .Net TryValidateObject - 如何本地化?

我有一個學生類:

public class Student 
    { 
     [Display(ResourceType = typeof(Strings), Name = @"Student_Name_DisplayName")] 
     [Required] 
     public string Name {get; set;} 
    } 

我有一個公共資源Strings.resx爲我的默認語言(英語)與

Key = Student_Name_DisplayName 
Value = Name 

我有一個內部的資源文件Strings.es。 RESX西班牙

Key = Student_Name_DisplayName 
Value = Nombre 

如果我創建一個新的Student對象,並且不將Name屬性設置一些事情,如果我調用Validator.TryValidateObject,我希望看到一個錯誤。我做。

將當前的文化和UI文化設置爲英文,出現驗證錯誤: 「名稱字段是必需的。」

將當前的Culture和UI文化設置爲西班牙語,出現驗證錯誤: 「The Nombre field is required。」

非常接近,但我希望留言的其他部分也用西班牙語。

我發現這樣做在Silverlight的作品 - Silveright以某種方式「看到」正確的語言,並得到我正確的錯誤。但是,我有一些服務器端處理,我也想返回正確的翻譯字符串。

完整的代碼如下:

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" 

的思考?

感謝(格拉西亞斯)

回答

0

您需要爲[Required]屬性(例如ErrorMessageResourceName)的本地化屬性指定值。

http://haacked.com/archive/2009/12/11/localizing-aspnetmvc-validation.aspx

+0

通過Silverlight的驗證展望(通過數據綁定XAML)我發現Silverlight那樣在這樣的情況下,給出正確的消息,完全轉換,而不必在Required屬性中提供任何參數。顯然,它經歷了一些其他的翻譯層,直接.Net,因爲我寫了它不。我想知道那層是什麼? (感謝您的示例鏈接 - 如果您不需要在「必需的」錯誤消息中說明字段的名稱,它就會起作用。此時,如果可能,我希望這樣做。謝謝。 –