ValidationAttribute.ErrorMessage中的替换参数

时间:2013-03-04 01:28:15

标签: asp.net-mvc validation

在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."

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

1 个答案:

答案 0 :(得分:16)

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

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