Question

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.

Was it helpful?

Solution

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;}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top