2012-12-20 46 views
2

場景: - 我正在開發MVC 4應用程序,該網站將以多種語言運行,並將託管在Azure上。 對於本地化我們依賴於數據庫而不是資源包方式。MVC 4從數據庫本地化驗證消息

問題: - 我想在運行時自定義錯誤消息,我想通過數據庫本地化消息。

我試圖通過反射改變屬性值,但它沒有奏效。

代碼: -

 //Model 
     public class Home 
     { 
      [Required(ErrorMessage = "Hard coded error msg")] 
      public string LogoutLabel { get; set; } 
     } 

    //On controller 
     public ActionResult Index() 
    { 
     Home homeData = new Home(); 
     foreach (PropertyInfo prop in homeData.GetType().GetProperties()) 
     { 
      foreach (Attribute attribute in prop.GetCustomAttributes(false)) 
      { 

       RequiredAttribute rerd = attribute as RequiredAttribute; 

       if (rerd != null) 
       { 
        rerd.ErrorMessage = "dynamic message"; 
       } 
      } 


     } 

     return View(homeData); 
    } 

在客戶端驗證時需要把它顯示我舊消息「硬編碼錯誤味精」。 如果我們不想使用資源綁定方法,請建議如何自定義這個方法

+0

我這裏udescribed我的方法: http://stackoverflow.com/questions/19398691/mvc-localisation-from-the-database-that- cover-all-messages-required-displayna –

回答

1

你打算實現這個嵌套循環來本地化你所有實體的驗證消息嗎?我認爲沒有更好的解決方案是使用Validator屬性。

爲找你等級:

[Validator(typeof(HomeValidator))] 
public class Home 
     {    
      public string LogoutLabel { get; set; } 
     } 

現在可以實現HomeValidator:

public class HomeValidator : AbstractValidator<Home> 
    { 
     public HomeValidator() 
     { 
      RuleFor(x => x.LogoutLabel).NotEmpty().WithMessage("your localized message"); 
     } 
    } 
+0

但是在這種情況下,我必須爲可用的驗證器編寫規則。只更改消息是不可能的? – Deepesh

+0

然後只更改消息:RuleFor(x => x.LogoutLabel).WithMessage(「您的本地化消息」); –

+0

似乎很有趣讓我檢查,所以在這種情況下,驗證空或其他人將工作在它就像是如果模型有多個屬性,並且每個屬性具有不同的驗證註釋,那麼此解決方案將工作? – Deepesh