Asp.net mvc 2 如何仅使用Viewmodel中的部分字段进行验证?

Asp.net mvc 2 如何仅使用Viewmodel中的部分字段进行验证?,asp.net-mvc-2,viewmodel,validation,Asp.net Mvc 2,Viewmodel,Validation,我的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 {ge

我的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}
}
有两个表单获取此viewmodel,表单中的用户输入apProperty1、apProperty2等,而BProperty-s返回为null。 FormB也一样。 表单类型(FormA或FormB)分配给ViewModel.type字段

所以问题是,在我的控制器中,我检查ModelState.IsValid属性,它在两种情况下都将为false,因为有一半字段始终为null

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


还有其他解决办法吗?(最好能够与客户端验证一起使用)

如果两个不同的视图只需要一个ViewModel,那么“部分验证”可能是您的解决方案。查看此博客:


IMO这里的问题是,您的“视图模型”与实际视图模型不匹配。你应该把它分开。我知道这是一个错误的方法,也是这里问题的主要来源,但这是一个要求。