【问题标题】:Custom Validation Attribute with Custom Model Binder in MVC 2MVC 2 中带有自定义模型绑定器的自定义验证属性
【发布时间】:2010-06-18 13:47:26
【问题描述】:

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

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

自定义模型绑定器;

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();

【问题讨论】:

  • 从技术上讲,您并没有真正使用自定义模型绑定器进行任何模型绑定。这只是使用模型绑定器进行验证(这不是模型绑定器的用途)。如果您确实需要对电话号码长度进行单独验证,这也可以是一个属性。
  • @Derek,虽然我同意你的观点,但我正在用这个作为例子向这里的人展示什么是可能的。我也有适当的绑定代码,我在这里展示的只是一个 sn-p

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


【解决方案1】:

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

【讨论】:

  • 啊啊啊啊!刚刚检查了SVN。我今天早上出于某种愚蠢的原因将其删除并忘记了!谢谢@Darin。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 2011-03-26
  • 1970-01-01
相关资源
最近更新 更多