我在我的模型中使用ASP.NET MVC 3和數據註解,並且想要從數據庫中檢索錯誤消息。所以我寫了繼承屬性:ASP.NET MVC - 「驗證類型名稱必須是唯一的。」
public class LocalizedRequiredAttribute : RequiredAttribute
{
public LocalizedRequiredAttribute(){}
public override string FormatErrorMessage(string name)
{
return GetByKeyHelper.GetByKey(this.ErrorMessage);
}
}
public class LocalizedRegularExpressionAttribute : RegularExpressionAttribute
{
public LocalizedRegularExpressionAttribute(string pattern) : base(pattern){}
public override string FormatErrorMessage(string name)
{
return GetByKeyHelper.GetByKey(this.ErrorMessage);
}
}
我寫2「適配器」這些屬性,以使客戶端驗證,比如這個:
public class LocalizedRequiredAttributeAdapter : DataAnnotationsModelValidator<LocalizedRequiredAttribute>
{
public LocalizedRequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, LocalizedRequiredAttribute attribute)
: base(metadata, context, attribute)
{
}
public static void SelfRegister()
{
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(LocalizedRequiredAttribute), typeof(RequiredAttributeAdapter));
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
return new[] { new ModelClientValidationRequiredRule(ErrorMessage) };
}
}
在我的Global.asax我有這兩條線:
LocalizedRegularExpressionAttributeAdapter.SelfRegister();
LocalizedRequiredAttributeAdapter.SelfRegister();
我得到一個異常「低調中的客戶端驗證規則驗證類型名稱必須是唯一的下列驗證類型被視爲不止一次:需要」時,我的模型呈現HTM L爲此屬性:
[LocalizedRequired(ErrorMessage = "global_Required_AccountName")]
[LocalizedRegularExpression(User.ADAccountMask, ErrorMessage = "global_Regex_AccountName")]
public string AccountName { get; set; }
什麼是錯?
是的,你是對的,但與此我有同樣的InvalidOperationException。 – asdfghjkl