How can I validate using DataAnnotations only part of fields in Viewmodel?

I've got a Viewmodel that looks like this:

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}
}

There are 2 forms that get this viewmodel and in FormA user inputs AProperty1, AProperty2 etc. and BProperty-s return as null. The same with FormB. The type of form (FormA or FormB) is assigned to the ViewModel.type field.

So the problem is that in my controller I check the ModelState.IsValid property and it'll be false in both ways because half of the fields are always null.

One possible solution could be to somehow override ModelState.IsValid property in my ModelView so that I could pass the type to it. But as far as i know there is no way to.

Are there any other solutions? (it preferrably should be able to use with client-side validation)

Answers


If it is really a requirement to have only one ViewModel for two different views, "Partial Validation" could be your solution. Check out this blog:

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


Need Your Help

Jenkins python api authentication “403 forbidden”

python jenkins urllib2

I'm trying to use jenkinsapi python library to work with Jenkins. My Jenkins is setup to authenticate with LDAP (with Active Directory Plugin). However, when I run my script to authenticate I fails