【问题标题】:Needing to copy properties before validation验证前需要复制属性
【发布时间】:2010-05-25 08:01:42
【问题描述】:

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

我的操作看起来像这样:

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

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

【问题讨论】:

  • farily = 公平还是真实?

标签: asp.net-mvc validation modelstate


【解决方案1】:

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

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

这个 CustomModelBinder 应该负责复制字段,并且因为它应用于 action 参数,所以它只会在这个 action 中使用。

【讨论】:

  • 但是我将如何检索从表单中发布的所有值呢?
  • TryUpdateModel() 将尝试将表单中的值放入您的客户对象中(这里唯一可能出错的是 TryUpdateModel 将缺少的字段设置为 null 并导致模型验证失败),只需给它试一试。
  • 这就是发生的事情,因为 CopyProperties 所做的只是使用诸如 Name 之类的属性并将其复制到 Name 的addresses 属性中,如果 Name 为空,您可以找出其余的 :)
  • 好的,所以我将我的答案重新定义为更适合这种情况的内容。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    我解决它有点不同,不确定这是否是最好的方法但是:

    首先我为 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 2018-03-20
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多