【问题标题】:Model binding validation errors模型绑定验证错误
【发布时间】:2013-03-20 20:56:22
【问题描述】:

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

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

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

感谢您的帮助! 萨弗里斯

【问题讨论】:

    标签: asp.net-mvc-4 model-binding


    【解决方案1】:

    我认为您可能面临的问题是,一旦您通过自定义活页夹将这些值推送到另一个对象中,它们就不再与页面上的相同。

    具有 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) 那么一切都会好起来的。

    【讨论】:

      猜你喜欢
      • 2013-08-02
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 2014-08-08
      • 1970-01-01
      • 2012-01-29
      相关资源
      最近更新 更多