在我的自定義模型驗證,我有以下幾點:模型綁定驗證錯誤
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