1

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

我的动作看起来像这样:

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

但它总是返回 false,并且 ModelState.IsValid 继续为 false。

4

3 回答 3

3

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

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

此 CustomModelBinder 应负责复制字段,并且由于它应用于操作参数,因此它将仅在此操作中使用。

于 2010-05-25T08:10:56.397 回答
1

Binder 正在处理表单值。所以,你的 ModelState 总是抛出一个错误。您必须检查实体中的属性或第二个选项编写您自己的模型活页夹。例如。

public class Customer
{
    public bool IsValid()
    {
        //TODO: check properties.
    }
}

public ActionResult Register(WebCustomer customer) 
{
    customer.CopyProperties();
    TryUpdateModel(customer);
    if (customer.IsValid())
    {
        ...
    }
    ...
于 2010-05-25T09:33:50.457 回答
1

我以不同的方式解决了它,不确定这是否是最好的方法,但是:

首先我为 ModelStateDictionary 做了一个扩展方法

public static void ResetErrors(this ModelStateDictionary modelState)
{
     foreach (var error in modelState.Values.Select(m => m.Errors))
 {
    error.Clear();
 }
}

然后我在我的行动中做了以下事情:

ModelState.ResetErrors();
customer.CopyProperties();
ValidateModel(customer);
于 2010-05-25T09:34:01.453 回答