0

在我的自定义模型验证中,我有以下内容:

 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) 并且我的视图需要视图模型,我该如何显示错误?

有什么方法可以确保在视图模型上出现验证错误时,控制器不会转换为持久数据模型?即使我们确实检查了数据对象中的所有模型错误并找到了验证错误,我们如何将用户发送回他们刚刚所在的视图,错误出现在他们所在的文本框旁边。

谢谢您的帮助!萨弗里斯

4

1 回答 1

0

I think the issue you may be facing is that once you push those values into the other object through the custom binder they are no longer the same as they were on the page.

A property called "PropertyValue" with an Html.ValidationFor(x=>x.PropertyValue) is going to look in the ModelState error collection for items with PropertyValue.

Once you have pushed those into Contact now the value is Contact.PropertyValue. If you validated it then it will be added to the ModelState as "Contact.PropertyValue" This will only be picked up by Html.ValidationFor(x=>x.Contact.PropertyValue)

The easiest solution is to make sure that your input and output's follow the same structure. If you can render the items as Html.TextBoxFor(x=>x.Contact.SomeProperty) then things will be fine.

于 2013-03-22T19:37:40.040 回答