2013-03-20 94 views
0

在我的自定義模型驗證,我有以下幾點:模型綁定驗證錯誤

public ActionResult Update([ModelBinder(typeof(ModelBinder.ContactModelBinder))] USR.USRContact contact) 
    { 
     if (ModelState.IsValid) 
     { 
      repository.Update(); 
      return View("~/Views/Shared/Contacts/ShowContactInfo.cshtml", repository.GetContactByID(contact.ContactID)); 
     } 
} 

}

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext){ 
     var repository = DependencyResolver.Current.GetService(typeof(IContactRepository)); 
     IContactRepository repo = repository as IContactRepository; 
     USRContact c = repo.GetContactByID(Convert.ToInt64(bindingContext.ValueProvider.GetValue("ContactID").AttemptedValue)); 
     c.FormalName = bindingContext.ValueProvider.GetValue("FormalName").AttemptedValue; 

     if (!repo.IsValidFormalName(c.ContactID, c.FormalName)) 
     { 
      var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 

      bindingContext.ModelState.AddModelError("FormalName", Resources.ErrorMsgs.FormalNameNotUnique); 

      return bindingContext.Model; 
     } 

     c.PreferredName = bindingContext.ValueProvider.GetValue("PreferredName").AttemptedValue; 
     c.Alias = bindingContext.ValueProvider.GetValue("Alias").AttemptedValue; 
     c.Pseudonym = bindingContext.ValueProvider.GetValue("Pseudonym").AttemptedValue; 
     c.GenderID = Convert.ToInt32(bindingContext.ValueProvider.GetValue("GenderID").AttemptedValue); 
     c.NationalityID = Convert.ToInt32(bindingContext.ValueProvider.GetValue("NationalityID").AttemptedValue); 
     c.ModifiedByID = Utilities.SessionUtil.Current.UserID; 
     c.ModifiedDate = DateTime.Now; 

}

我控制器通過以下操作調用此模型綁定

我的viewmodel包含數據註釋,表示需要正式名稱,而其他需要少於60個字符。如果模型聯編程序將其轉換爲持久數據模型(USRContact)並且我的視圖期待視圖模型,如何顯示錯誤?

有什麼辦法可以確保視圖模型上的驗證錯誤,控制器不會轉換爲持久數據模型?即使我們檢查數據對象中的所有模型錯誤並找到驗證錯誤,我們如何將用戶返回到他們剛剛在錯誤文本框旁邊出現錯誤的視圖中。

感謝您的幫助! Safris

回答

0

我認爲您可能面臨的問題是,一旦您通過自定義聯編程序將這些值推入另一個對象,它們將不再與頁面上的相同。

帶有Html.ValidationFor(x => x.PropertyValue)的名爲「PropertyValue」的屬性將在ModelState錯誤集合中查找包含PropertyValue的項目。

將這些內容推送到Contact後,值爲Contact.PropertyValue。如果您驗證了它,那麼它將作爲「Contact.PropertyValue」添加到ModelState中,這將只會被Html.ValidationFor(x => x.Contact.PropertyValue)拾取。

最簡單的解決方案是確保你的輸入和輸出遵循相同的結構。如果你可以渲染項目爲Html.TextBoxFor(x => x.Contact.SomeProperty),那麼事情會很好。