MVC 2中自定义模型绑定器的自定义验证属性

时间:2010-06-18 04:26:33

标签: asp.net-mvc custom-validators custom-model-binder

我为我所包含的代码量道歉。我试图将它保持在最低限度。

我正在尝试在我的模型上使用自定义验证器属性以及自定义模型绑定器。属性和Binder分开工作很好但如果我同时使用,则验证属性不再有效。

这是为了便于阅读而剪切了我的代码。如果我省略了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; }

Custom Model Binder;

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.");
    }
}

全球性的asax;

System.Web.Mvc.ModelBinders.Binders[typeof(ContactFormViewModel)] = 
  new CustomContactUsBinder();

1 个答案:

答案 0 :(得分:6)

确保您正在调用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);
}