如何将DisplayName放在ErrorMessage格式上

goe*_*ing 24 c# asp.net-mvc data-annotations

我有这样的事情:

    [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; }
Run Code Online (Sandbox Code Playgroud)

我想要以下输出:

  • 名字是必需的.
  • 名字的长度应在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);
Run Code Online (Sandbox Code Playgroud)

结果是:

  • 名称是必需的.
  • 姓名的长度应在10到50之间.

怎么了?谢谢.

Sor*_*sen 36

而不是(或可能与)一起使用[DisplayName]属性,使用[Display]in中的属性System.ComponentModel.DataAnnotations.填充其Name财产.

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

例如,

[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; }
Run Code Online (Sandbox Code Playgroud)

  • 对不起,我不记得了。[来源失忆症](https://en.wikipedia.org/wiki/Source_amnesia) 再次来袭。尽管如此,我可以非常自信地说我没有从 MSDN 文档中阅读它。 (2认同)

goe*_*ing 11

好吧,我想我做到了.

我必须创建另一个属性,如下所示:

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);
    } 
}
Run Code Online (Sandbox Code Playgroud)

我的模型是:

    [DisplayName("Full name")]
    [Required]
    public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

值得庆幸的是,这个DataAnnotation是可扩展的.