简体   繁体   English

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

[英]Custom Validation Attribute with Custom Model Binder in MVC 2

I apologise for the amount of code I have included. 我为我所包含的代码量道歉。 I've tried to keep it to a minimum. 我试图将它保持在最低限度。

I'm trying to have a Custom Validator Attribute on my model as well as a Custom Model binder. 我正在尝试在我的模型上使用自定义验证器属性以及自定义模型绑定器。 The Attribute and the Binder work great seperately but if I have both, then the Validation Attribute no longer works. 属性和Binder分开工作很好,但如果我同时使用,则验证属性不再有效。

Here is my code snipped for readability. 这是我的代码剪切的可读性。 If I leave out the code in global.asax the custom validation fires but not if I have the custom binder enabled. 如果我省略了global.asax中的代码,则会启动自定义验证,但如果我启用了自定义绑定,则不会触发。

Validation Attribute; 验证属性;

public class IsPhoneNumberAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        //do some checking on 'value' here
        return true;
    }
}

Useage of the attribute in my model; 在我的模型中使用属性;

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

Global asax; 全球性的;

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

Make sure you are calling the base method: 确保您正在调用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM