2010-06-18 231 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