Self referencing model with Required annotation on some properties in ASP.Net MVC5

141 Views Asked by At

I have this selfreferencing Model:

public class AddressDataViewModel
{
    [Required]
    public String Country {get; set;}

    public String Town {get; set;}

    public AddressDataViewModel AdditionalAddress {get; set;}
}

Problem is that the Required attribute is also applicated to the Country property of self referenced object AdditionalAddress and so on. Is there some easy way to suppress this? I only want Required validation to first of the hierarchy.

Thanks.

1

There are 1 best solutions below

0
On BEST ANSWER

You could solve this with a base and derived class:

public abstract class AddressDataViewModel
{

    public virtual String Country {get; set;}

    public String Town {get; set;}

}

public class PrimaryAddressDataViewModel : AddressDataViewModel
{

    [Required]
    public Overrides String Country {get; set;}

}

public class AdditionalAddressDataViewModel : AddressDataViewModel
{
}

public class AddressesDataViewModel
{
     public PrimaryAddressDataViewModel PrimaryAddress {get;set;}
     IEnumerable<AdditionalAddressDataViewModel> AdditionalAddresses {get;set;}
}