在C#属性中替换字符串

时间:2014-04-16 09:54:13

标签: c# asp.net-mvc attributes asp.net-mvc-5

创建新的MVC5应用程序时,有一个具有此属性的ViewModel:

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

我对这部分感兴趣:

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

我相信{0}[Display(Name = "New password")]获取字符串,而{2}MinimumLength = 6获取字符串。

我不明白,为什么他们按照这个特定的顺序?我的意思是为什么{2}而不是{1}MinimumLength = 6获得价值?同问{0}。我如何确定此订单?

下一个声明是否正确?我希望{0}获取显示名称和{1} - length: 25

[MinLength(length: 25, ErrorMessage = "Length of {0} must be at least {1} characters long.")]
[Display(Name = "My property")]
public string MyProperty { get; set; }

如果删除属性[Display(Name = "My property")]会怎样?在这种情况下,{0}只是取了我的属性"MyProperty"的名称吗?

感谢。

1 个答案:

答案 0 :(得分:1)

"他们按此特定顺序排列的原因是什么?"

订单是:

  1. Display Name
  2. MaximumLength
  3. MinimumLength
  4. 问题字符串frormat的答案采用 FormatErrorMessage StringLengthAttribute.cs 方法:

    public override string FormatErrorMessage(string name) {
        this.EnsureLegalLengths();
    
        bool useErrorMessageWithMinimum = this.MinimumLength != 0 && !this.CustomErrorMessageSet;
    
        string errorMessage = useErrorMessageWithMinimum ?
            DataAnnotationsResources.StringLengthAttribute_ValidationErrorIncludingMinimum : this.ErrorMessageString;
    
        // it's ok to pass in the minLength even for the error message without a {2} param since String.Format will just
        // ignore extra arguments
        return String.Format(CultureInfo.CurrentCulture, errorMessage, name, this.MaximumLength, this.MinimumLength);
    }
    

    "如果我删除属性[显示(姓名="我的属性")]会是什么?在这种情况下,{0}是否只取我的财产的名称" MyProperty"

    是的,它会使用会员名称。

    以下是DisplayName属性的代码,该代码作为 name 传递给 FormatErrorMessage

    public string DisplayName {
        get {
            if (string.IsNullOrEmpty(this._displayName)) {
                this._displayName = this.GetDisplayName();
    
                if (string.IsNullOrEmpty(this._displayName)) {
                    this._displayName = this.MemberName;
    
                    if (string.IsNullOrEmpty(this._displayName)) {
                        this._displayName = this.ObjectType.Name;
                    }
                }
            }
            return this._displayName;
        }   
    }