2013-03-20 124 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),那么事情会很好。