2012-12-20 47 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