Search code examples
asp.net-mvc-3data-annotationsmodelstate

Require property if parent class is required


I have a problem with MVC3 model validation and DataAnnotations

I have the following classes:

public class A
{
    public C SomeProperty {get;set;}
}

public class B
{
    [Required]
    public C SomeProperty {get;set;}
}
public class C
{
    [Required]
    public string SomeSubProperty {get;set;}
}

This is because C can be required for some objects and not required for others, but if C is required i want SomeSubProperty to also be required.

However when i call ModelState.IsValid in my controller it will return false when using both A and B as models if SomeSubProperty is not set. Is there any way i can produce this behaviour?


Solution

  • I don't normally mix "Domain Model" with "View Model".

    Domain model reflects business relationship and it can be very complex whereas view model suppose to be very flat and doesn't have deep levels of dependencies so that you are able to use Annotations.