在我的自定义模型验证,我有以下几点:模型绑定验证错误
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