BattlFrog BattlFrog - 29 days ago 7x
jQuery Question

Using [RequiredIf] in ASP MVC3 with ViewModels

I am using the custom RequiredIf attribute created by Simon Ince in my MVC app.

I have a viewmodel which is passed to the view like this:

public class HistoryViewModel
public Contact ContactModel { get; set; }
public Account AccountModel { get; set; }
public Person PersonModel { get; set; }

I have a bunch of models with all the props in them (i.e. contact.cs, account.cs, person.cs)

public class Person
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsAdult { get; set; }
[RequiredIf("IsAdult", "Yes", Errormessage="Please leave a comment")]
public string Comments { get; set; }

validation does not seem to be working when passed through the viewmodel. It works fine if I move the properties into the viewmodel directly
. All other
[Required]` attributes work from the model, through the viewmodel.

So do I need to move all the properties into the viewmodel, that need the RequiredIf on them? Or is there another way around this?


Have you tried MVC FoolProof validation? It has support for RequiredIf (and a fair few others) with Client Side support. It can sometimes be a bit buggy but latest version isn't to bad.

Works in same way as the above (which I tried before I switched to FoolProof)

   public bool Married { get; set; }

    public string MaidenName { get; set; }