Search code examples
asp.net-mvcvalidationrequiredself-reference

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


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.


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;}
    }