Question

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?

Was it helpful?

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.

OTHER TIPS

Take a look at AutoMapper. Define each ViewModel with its specific requirements, and map it to the domain model for processing once validation has succeeded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top