【问题标题】:How can I validate using DataAnnotations only part of fields in Viewmodel?如何仅使用 DataAnnotations 验证 Viewmodel 中的部分字段?
【发布时间】:2010-12-03 09:03:36
【问题描述】:

我有一个看起来像这样的 Viewmodel:

public class Viewmodel
{

  public int Type {get;set} // 0 if typeA, 1 if typeB

  [Required]
  public string AProperty1 {get;set}

  [Required]
  public string AProperty1 {get;set}

  ...

  [Required]
  public string BProperty1 {get;set}

  [Required]
  public string BProperty1 {get;set}
}

有 2 个表单可以获取此视图模型,并且在 FormA 中用户输入 AProperty1、AProperty2 等,而 BProperty-s 返回为 null。 与 FormB 相同。 表单的类型(FormA 或 FormB)分配给 ViewModel.type 字段。

所以问题是,在我的控制器中,我检查了 ModelState.IsValid 属性,但由于一半的字段始终为空,所以这两种方式都是错误的。

一种可能的解决方案是在我的 ModelView 中以某种方式覆盖 ModelState.IsValid 属性,以便我可以将类型传递给它。但据我所知没有办法。

还有其他解决方案吗? (它最好应该能够与客户端验证一起使用)

【问题讨论】:

  • IMO 这里的问题是您的“ViewModel”不适合您的真实视图模型。你应该把它分开。
  • 我知道这是一种错误的方式,也是问题的主要来源,但这是一个要求。

标签: asp.net-mvc-2 viewmodel validation


【解决方案1】:

如果确实需要一个 ViewModel 用于两个不同的视图,“部分验证”可能是您的解决方案。看看这个博客:

http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多