对于我包含的代码量,我深表歉意。我试图将其保持在最低限度。
我正在尝试在我的模型上使用自定义验证器属性以及自定义模型活页夹。 Attribute 和 Binder 单独工作很好,但如果我同时拥有,那么 Validation Attribute 将不再工作。
这是我为便于阅读而截取的代码。如果我在 global.asax 中遗漏了代码,则会触发自定义验证,但如果我启用了自定义活页夹,则不会触发。
验证属性;
public class IsPhoneNumberAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//do some checking on 'value' here
return true;
}
}
我的模型中属性的使用;
[Required(ErrorMessage = "Please provide a contact number")]
[IsPhoneNumberAttribute(ErrorMessage = "Not a valid phone number")]
public string Phone { get; set; }
自定义模型绑定(bind)器;
public class CustomContactUsBinder : DefaultModelBinder
{
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ContactFormViewModel contactFormViewModel = bindingContext.Model as ContactFormViewModel;
if (!String.IsNullOrEmpty(contactFormViewModel.Phone))
if (contactFormViewModel.Phone.Length > 10)
bindingContext.ModelState.AddModelError("Phone", "Phone is too long.");
}
}
全局阿萨克斯;
System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] =
new CustomContactUsBinder();
最佳答案
确保您调用 base
方法:
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ContactFormViewModel contactFormViewModel = bindingContext.Model as ContactFormViewModel;
if (!String.IsNullOrEmpty(contactFormViewModel.Phone))
if (contactFormViewModel.Phone.Length > 10)
bindingContext.ModelState.AddModelError("Phone", "Phone is too long.");
base.OnModelUpdated(controllerContext, bindingContext);
}
关于asp.net-mvc - MVC 2 中带有自定义模型绑定(bind)器的自定义验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3067204/