我已經創建了一個自定義的ASP.NET MVC ValidationAttribute,並且試圖通過將一個字符串傳遞給基礎構造函數來在實例化時爲其設置自己的默認錯誤消息:爲自定義ASP.NET MVC驗證屬性設置默認的ErrorMessage
public class BusinessLogicRegex : ValidationAttribute, IClientValidatable
{
private const string _defaultErrorMessage = "Invalid Password. {0}";
private string _description;
//Other private members
...
public BusinessLogicRegex(string getMember, Type getMemberType, string descriptionMember, Type descriptionMemberType)
: base(_defaultErrorMessage)
{
//Omitted the guts of initializing validation for brevity
...
}
public override string FormatErrorMessage(string name)
{
return String.Format(ErrorMessage, _description);
}
}
但是,當調用FormatErrorMessage時,ErrorMessage爲null。爲什麼base(_defaultErrorMessage)
這個base(_defaultErrorMessage)
沒有設置ErrorMessage屬性,我應該如何設置它,同時仍然給這個屬性的用戶覆蓋它的能力?
編輯 - 2,清潔例子:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class TestValidator : ValidationAttribute
{
public TestValidator()
: base("Test Error on {0}")
{
}
public override string FormatErrorMessage(string name)
{
return String.Format(ErrorMessage, name);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
}
在這裏,FormatErrorMessage拋出一個空引用異常,因爲ErrorMessage
爲空。但是ErrorMessageString
==「在{0}上測試錯誤」。所以我的錯誤似乎認爲調用base("Test Error on {0}")
設置ErrorMessage屬性。我根本不明白這一點。在此基礎構造如何描述其errorMessage
參數:
錯誤信息與驗證控件
這裏關聯是什麼MSDN說對ErrorMessageString
屬性:
錯誤信息字符串是通過評估ErrorMessage屬性或通過評估ErrorMessageResourceType和ErrorMessageResourceName屬性獲得的。這兩種情況是相互排斥的。如果要顯示本地化的錯誤消息,則使用第二種情況。
然而FormatErrorMessage內運行時,ErrorMessage
,ErrorMessageResourceType
和ErrorMessageResourceName
均爲空。所以這個描述聽起來像ErrorMessageString
也應該爲null。這讓我對所有這些屬性和構造函數之間的使用和交互感到困惑。
它應該是'返回的String.Format(ErrorMessageString,名);' –
不,我娃nt在那裏顯示_description。我應該把'name'放在默認的消息中。但它是'ErrorMessage',它是null。 – xr280xr
這正是將要做的事!試試吧 –