【问题标题】:Setting a Custom error message in an Compare Attribute in .net mvc在 .net mvc 的比较属性中设置自定义错误消息
【发布时间】:2017-12-01 14:34:35
【问题描述】:

我正在尝试将两个密码字段与比较属性进行比较,在我的项目中,我使用 HTML 帮助程序根据语言 ID 获取不同语言的消息,但我无法在错误消息中使用我的方法

[LocalizedRequired("PasswordRequired")]
        public string Password { get; set; }
        
        [LocalizedRequired("PasswordDoesntMatch")]
        [System.ComponentModel.DataAnnotations.CompareAttribute("Password", ErrorMessage = "Password doesn't match.")]
        public string ConfirmPassowrd { get; set; }

这是没有助手的模型,它工作正常,问题是如果我使用任何返回字符串错误消息的方法,它根本不起作用。

[LocalizedRequired("PasswordRequired")]
        public string Password { get; set; }
        
        [LocalizedRequired("PasswordDoesntMatch")]
        [System.ComponentModel.DataAnnotations.CompareAttribute("Password", ErrorMessage = Kuvendi.Infrastructure.MVC.HtmlHelperExtensions.DrawLabel("Password doesn't match")))]
        public string ConfirmPassowrd { get; set; }

Draw label是一个HTML helper方法,它返回特定语言id的字符串,helper成功返回字符串并经过测试。

感谢您的宝贵时间。

【问题讨论】:

  • “根本不起作用”:请在问题中显示您的非工作代码解释它与您的不同之处期待。
  • 好的,我现在就编辑它

标签: c# .net asp.net-mvc


【解决方案1】:

传递给属性的参数必须是编译时常量,所以不能调用任何辅助方法来生成它们。

但是,您可以提供字符串资源的名称和资源文件。语言 will be resolved 由 MVC 和来自正确资源文件的翻译将被选择。

[LocalizedRequired("PasswordDoesntMatch")]
[System.ComponentModel.DataAnnotations.CompareAttribute("Password", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "PasswordDoesntMatch")]
public string ConfirmPassowrd { get; set; }

【讨论】:

  • 资源类型“MySql.Data.Resources”没有名为“PasswordDoesntMatch”的可访问静态属性。 System.InvalidOperationException:资源类型“MySql.Data.Resources”没有名为“PasswordDoesntMatch”的可访问静态属性。
  • 这是这段代码返回给我的错误信息
  • 是的,Resources.resx 文件必须存在并且包含带有键 PasswordDoesntMatch 的字符串资源。还要确保您的 MVC 项目设置为传递正确的语言(请参阅我的帖子中的链接)。
  • 这是否意味着我可以使用不同的标签并且它会起作用??
  • 然后它应该在Resources.en.resxResources.fr.resx等中查找翻译,具体取决于Thread.CurrentThread.CurrentUICulture。后备将是Resources.resx
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多