验证前需要复制属性 [英] Needing to copy properties before validation

查看:50
本文介绍了验证前需要复制属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当复杂的模型需要验证,问题在于该模型在两个不同的地方使用,一个在您注册客户的地方,一个在简单地添加地址的地方.地址上的某些字段在注册客户表单上根本不可见.因此,当我检查是否ModelState.IsValid时,我当然会得到错误,例如.名称未在帐单地址上输入,但在客户上.这就是为什么我想在验证发生之前将几个字段复制到模型,然后进行验证的原因.我虽然有些失落,但需要帮助.

I have a fairly complex model needing to be validated, the problem is that this model is used on two different places, one where you register your customer and one where you simply add addresses. Some fields on the address are simply not visible on the register customer form. So when i check if ModelState.IsValid i get false of course since eg. the name is not entered on the billing address, but it is on the customer. That is why i want to before validation occurs, copy a couple of fields to the model, and then validate. I am somewhat lost though and i need help.

我的动作如下所示:

public ActionResult Register(WebCustomer customer) 
{
     customer.CopyProperties();
     if(TryUpdateModel(customer)) 
     {
       ...
     }
     ...

但是它总是返回false,而ModelState.IsValid继续为false.

But it always returns false, and ModelState.IsValid continues to be false.

推荐答案

在这种情况下,我认为最好的方法是编写CustomModelBinder并将其应用于您的操作参数

I think that the best approach in this situation, is to write CustomModelBinder, and apply it to your action parameter

public ActionResult Register([ModelBinder(typeof(WebCustomerRegisterBinder))]WebCustomer customer)  
{
  if(TryUpdateModel(customer))  
  { 
    ... 
  } 
  ...
}

此CustomModelBinder应该负责复制字段,并且由于将其应用于操作参数,因此只能在此操作中使用.

This CustomModelBinder should take care of copying fields, and because its applied to action parameter it will be used only in this action.

这篇关于验证前需要复制属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆