asp.net-mvc - MVC 2 中带有自定义模型绑定(bind)器的自定义验证属性

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

对于我包含的代码量,我深表歉意。我试图将其保持在最低限度。

我正在尝试在我的模型上使用自定义验证器属性以及自定义模型活页夹。 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/

相关文章:

c# - 如何在 Asp.Net MVC 4 的多态模型中绑定(bind)复杂属性?

c# - 类型可为空时不调用自定义模型联编程序

c# - ASPNET MVC - 为什么 ModelState.IsValid false "The x field is required"当该字段确实有值时?

c# - 我有一个 POCO,我可以从 DbContext 获得代理吗?

asp.net-mvc - 当参数名称需要不同时,如何重用远程验证方法?

ruby-on-rails - 在 Rails 应用程序中独立于模型测试自定义验证功能

javascript - 使用自定义验证器防止将来的日期和今天的日期

css - 是否可以为特定的 MVC View 指定 CSS 类?

ruby-on-rails-3 - Rails 3 : displaying error full messages in flash message

asp.net-mvc - 自定义模型绑定(bind)器不验证模型