gpt4 book ai didi

asp.net-mvc - ValidationAttribute.ErrorMessage 中的替换参数

转载 作者:行者123 更新时间:2023-12-03 23:41:47 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于asp.net-mvc - ValidationAttribute.ErrorMessage 中的替换参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15193145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com