【问题标题】:Substitution arguments in ValidationAttribute.ErrorMessageValidationAttribute.ErrorMessage 中的替换参数
【发布时间】:2013-03-04 01:28:14
【问题描述】:

在 ASP.NET MVC 4 应用程序中,LocalPasswordModel 类(在 Models\AccountModels.cs 中)如下所示:

public class LocalPasswordModel
{
    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Current password")]
    public string OldPassword { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "New password")]
    public string NewPassword { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm new password")]
    [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

上面的代码在 ErrorMessage 字符串中包含两个替换参数:

ErrorMessage = "The {0} must be at least {2} characters long."

有人能告诉我替换到该字符串中的值来自哪里吗?更一般地说,是否有任何近似官方文档来描述参数替换在这种情况下如何工作?

【问题讨论】:

    标签: asp.net-mvc validation


    【解决方案1】:

    对于StringLengthAttribute,消息字符串可以有3个参数:

    {0} Property name
    {1} Maximum length
    {2} Minimum length
    

    不幸的是,这些参数似乎没有很好的文档记录。这些值是从每个验证属性的FormatErrorMessage 属性传入的。例如,使用 .NET Reflector,这是来自StringLengthAttribute 的方法:

    public override string FormatErrorMessage(string name)
    {
        EnsureLegalLengths();
        string format = ((this.MinimumLength != 0) && !base.CustomErrorMessageSet) ? DataAnnotationsResources.StringLengthAttribute_ValidationErrorIncludingMinimum : base.ErrorMessageString;
        return String.Format(CultureInfo.CurrentCulture, format, new object[] { name, MaximumLength, MinimumLength });
    }
    

    可以安全地假设这永远不会改变,因为这会破坏几乎所有使用它的应用程序。

    【讨论】:

    • 请注意,这些是无序的 - {0} 是属性名称,{1}最大 长度,{2}最小 长度。 (参见代码块中对 String.Format 的调用。)
    • @GalacticCowboy 谢谢,我修好了。显然其他人很久以前编辑了我的答案并将不正确的文本放在那里。
    猜你喜欢
    • 2016-09-08
    • 2014-11-10
    • 1970-01-01
    • 2013-06-29
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多