覆盖 MVC 中的最大长度错误消息

Override max length error message in MVC

我正在尝试覆盖 ASP.net MVC 中的最大长度错误消息。基本上,我想使错误消息字符串如下:

[DisplayName] 长度不应超过 [x]。但是,我不知道如何在里面包含displayname属性值。

public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "What should I input here"
    }
}

如果使用StringLengthAttribute {0}指的是显示名称,{2}指的是长度。

public class MyMaxLengthAttribute : StringLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "{0} length should not be more than {2}"
    }
}

嗨,我这里没有电脑,但我相信你必须按照以下方式做一些事情。

public class MyMaxLengthAttribute : MaxLengthAttribute
{
     private static String CustomErrorMessage = "{0} length should not be more than {1}";
     public MyMaxLengthAttribute(int length) : base(length)
     {
         ErrorMessage = "What should I input here"
     }

     public override string FormatErrorMessage(string name)
     {
        if (!String.IsNullOrEmpty(ErrorMessage))
        {
            ErrorMessage = MyErrorMessage;
        }
        return String.Format(CultureInfo.CurrentUICulture, CustomErrorMessage , name);
     }
}