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

3
我正在尝试覆盖ASP.net MVC中的最大长度错误消息。 基本上,我希望将错误消息字符串设置为以下内容:
"[DisplayName]"的长度不应超过[x]。 但是,我不知道如何在其中包含displayname属性值。
public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "What should I input here"
    }
}
2个回答

5
如果您使用StringLengthAttribute{0}表示显示名称,{2}表示长度。
public class MyMaxLengthAttribute : StringLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "{0} length should not be more than {2}"
    }
}

是的,这可能是我想要的。请问在哪里可以找到关于每个属性中{0}、{1}、{2}代表什么的参考资料?此外,是否有可能直接覆盖stringlength属性而不需要继承? - stackdisplay
@stackdisplay 我最终只是使用现有的一个进行了测试,即 [StringLength(100, ErrorMessage = "0: {0},1: {1}, 2: {2}, "。我找不到任何关于它的文档。 :) - hutchonoid
1
@stackdisplay 实际上有人在这里详细说明了。{0}索引是属性的显示名称,{1}是MaximumLength,{2}是MinimumLength。因此,您的错误消息将被格式化为“The Foo必须至少为6个字符长。” https://dev59.com/N2Yr5IYBdhLWcg3wvsvR - hutchonoid

1

您好,我这里没有电脑,但我认为您需要做一些类似于这样的操作。

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

嗨,重写 MyMaxLengthAttribute 中的 ErrorMessage 和 FormatErrorMessage 有什么区别?有什么优缺点吗?在我看来,两者都会得出相同的结果。 - stackdisplay
嗨,说实话我不确定。它们似乎在做相同的事情,但它们有不同的定义,即MSDN ErrorMessage / MSDN FormatErrorMessage - Mō Iđɍɨɇƶ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接