0

好的,所以我有一个看起来像这样的模型:

public class CustomerViewModel {
  public string Password { get; set; }
}

public class CustomerAddViewModel {
  public CustomerViewModel Customer { get; set; }
  [System.ComponentModel.DataAnnotations.Compare("Customer.Password", ErrorMessage = "The confirm password should match")]
  public string ConfirmPassword { get; set; }
}

我在验证时收到错误消息“找不到名为 Customer.Password 的属性”。

我找到了这个 SO Question,但它不适用,因为在最新版本的validation.unobtrusive 中,代码如下所示:

element = $(options.form).find(":input[name='" + escapeAttributeValue(fullOtherName) + "']")[0];

其中 escapeAttributeValue 处理所有有效的特殊字符。

我尝试改用 System.Web.Mvc.Compare,但这会在渲染视图时导致错误。

有任何想法吗?

4

2 回答 2

1

原因很简单,属性“Customer.Password”不存在。您可以像这样定义您的 ViewModel:

public class CustomerAddViewModel {
  public CustomerViewModel Customer { get; set; }
  public string Password 
  {
     get
     {
        return this.Customer.Password;
     }
  }
  [System.ComponentModel.DataAnnotations.Compare("Password", ErrorMessage = "The confirm password should match")]
  public string ConfirmPassword { get; set; }
}
于 2013-08-06T18:13:01.903 回答
0

做你正在做的事情的正确“MVC”方式是避免在你的视图模型中有子对象。视图模型用于提供特定操作所需的最少信息。您注册/创建客户所需的所有信息都应该在您的视图模型中,并且当您使用有效信息提交表单时,接收它的操作(或根据您的结构在数据层中的某个位置)将创建一个客户基于该视图模型的对象。

当然,您可能仍然可以绕过我刚才所说的内容,但是您拒绝写这些额外行的时间越长,就越难摆脱您正在挖掘的洞。

于 2013-08-06T18:18:18.600 回答