2010-06-18 128 views
3

我对我已经包含的代码数量道歉。我试图把它保持在最低限度。自定义验证使用自定义的模型绑定属性在MVC 2

我想对我的模型自定义验证属性以及自定义模型粘合剂。 Attribute和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."); 
    } 
} 

Global asax;

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

从技术上说,你是不是真的做任何模型与您的自定义模型粘结剂结合。这只是使用模型联编程序进行验证(这不是模型联编程序的用途)。如果您确实需要对电话号码长度进行单独验证,则这也可能是一个属性。 – 2010-06-22 22:32:26

+0

@Derek,虽然我同意你的看法,我用这个作为一个例子,这里什么是可能的家伙。我已经propper在那里绑定代码以及什么,我这里介绍的是一个片段只 – griegs 2010-06-22 22:54:35

回答

5

确保您所呼叫的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); 
} 
+0

AAAahhhh!刚刚检查SVN。今天早上我因为一些愚蠢的原因将它删除了,并且忘记了它!谢谢@Darin。 – griegs 2010-06-18 05:52:25