在我的自定义模型验证中,我有以下内容:
 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;
}
我的控制器通过执行以下操作调用此模型绑定器:
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));
        }
}
}
我的视图模型包含数据注释,说明需要正式名称并且别名需要少于 60 个字符。如果模型绑定器将其转换为持久数据模型 (USRContact) 并且我的视图需要视图模型,我该如何显示错误?
有什么方法可以确保在视图模型上出现验证错误时,控制器不会转换为持久数据模型?即使我们确实检查了数据对象中的所有模型错误并找到了验证错误,我们如何将用户发送回他们刚刚所在的视图,错误出现在他们所在的文本框旁边。
谢谢您的帮助!萨弗里斯