【问题标题】:MVC 4 Localising Validation Messages from DatabaseMVC 4 本地化来自数据库的验证消息
【发布时间】:2012-12-20 07:21:01
【问题描述】:

场景:- 我正在开发 MVC 4 应用程序,该网站将以多种语言运行,并将托管在 Azure 上。 对于本地化,我们依赖于数据库而不是资源包方法。

问题:- 我想在运行时自定义错误消息,我想通过数据库本地化消息。

我曾尝试通过反射来更改属性值,但没有成功。

代码:-

     //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);
    }  

在客户端进行验证时,它会向我显示旧消息“硬编码错误消息”。 如果我们不想使用资源包方法,请建议如何定制它

【问题讨论】:

标签: asp.net-mvc validation asp.net-mvc-4


【解决方案1】:

您最好创建并注册自己的 DataAnnotationsModelMetadataProvider,您可以在其中覆盖错误消息。有关更多详细信息,请在此处查看类似问题的答案MVC Validation Error Messages not hardcoded in Attributes

【讨论】:

    【解决方案2】:

    你打算实现这个嵌套循环来本地化你所有实体的验证消息吗?我认为没有。更好的解决方案是使用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");
            }
        }
    

    【讨论】:

    • 但在这种情况下,我必须为可用的验证器编写规则。不能只更改消息吗?
    • 然后只更改消息: RuleFor(x => x.LogoutLabel ).WithMessage("您的本地化消息");
    • 似乎很有趣让我检查一下,所以在这种情况下验证空或其他将起作用就像模型有多个属性并且每个属性都有不同的验证注释,那么这个解决方案也可以工作吗?
    • 当一个属性有多个验证时会发生什么,而且在这种方法中,我们必须显式处理每个属性,我们不能扩展属性以便以更通用的方式完成吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2017-03-02
    相关资源
    最近更新 更多