代码之家  ›  专栏  ›  技术社区  ›  goenning

如何将DisplayName设置为ErrorMessage格式

  •  22
  • goenning  · 技术社区  · 16 年前

    我有这样的东西:

        [DisplayName("First Name")]
        [Required(ErrorMessage="{0} is required.")]
        [StringLength(50, MinimumLength = 10, ErrorMessage="{0}'s length should be between {2} and {1}.")]
        public string Name { get; set; }
    

    我希望有以下输出:

    • 名字是必需的。
    • 名字的长度应该在10到50之间。

    它在使用ASP.NET MVC2错误摘要时工作 ,但当我尝试手动验证它时,如下所示:

            ValidationContext context = new ValidationContext(myModel, null, null);
            List<ValidationResult> results = new List<ValidationResult>();
            bool valid = Validator.TryValidateObject(myModel, context, results, true);
    

    结果是:

    • 名称是必需的。
    • 名称的长度应介于10和50之间。

    怎么了?谢谢。

    2 回复  |  直到 11 年前
        1
  •  33
  •   Sorensen    11 年前

    而不是(或可能与之结合)使用 [DisplayName] 属性,使用 [Display] 属性在 System.ComponentModel.DataAnnotations . 填充它的 Name 财产。

    这样,您就可以使用内置的验证属性或自定义属性 ValidationContext 的 DisplayName .

    例如。,

    [Display(Name="First Name")] // <-- Here
    [Required(ErrorMessage="{0} is required.")]
    [StringLength(50, MinimumLength = 10, ErrorMessage="{0}'s length should be between {2} and {1}.")]
    public string Name { get; set; }
    
        2
  •  10
  •   goenning    16 年前

    嗯,我想我做到了。

    我必须创建另一个这样的属性:

    public class RequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute
    {
        private String displayName;
    
        public RequiredAttribute()
        {
            this.ErrorMessage = "{0} is required";
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var attributes = validationContext.ObjectType.GetProperty(validationContext.MemberName).GetCustomAttributes(typeof(DisplayNameAttribute), true);
            if (attributes != null)
                this.displayName = (attributes[0] as DisplayNameAttribute).DisplayName;
            else
                this.displayName = validationContext.DisplayName;
    
            return base.IsValid(value, validationContext);
        }
    
        public override string FormatErrorMessage(string name)
        {
            return string.Format(this.ErrorMessageString, displayName);
        } 
    }
    

    我的模型是:

        [DisplayName("Full name")]
        [Required]
        public string Name { get; set; }
    

    幸运的是,这个数据注释是可扩展的。