Search code examples
c#asp.net-mvcdata-annotationsrequired

Disable required attribute


I have a class:

public class ShoppingParent : Parent 
{

}

Which implements this class:

public class Parent 
{

  public string Firstname { get; set;}

  public string Lastname { get; set;}

  public string Address { get; set;}

  public string Town { get; set;}

  [Required]
  public string Password { get; set;}

}

Because ShoppingCart implements the Parent class, the ModelState.Valid is always false because the Password is required but I don't populate it with data as it is not needed in the ShoppingParent class.

I'm trying to figure out how to disable the Password required within the ShoppingParent class but keep it required within the Parent class.

Does anyone know how to do this?


Solution

  • You can move the common properties to an interface and make each one decide if it's required or not.

    public interface IParent
    {
        string Firstname { get; set; }
        string Lastname { get; set; }
        string Address { get; set; }
        string Town { get; set; }
        string Password { get; set; }
    }
    
    public class ShoppingParent : IParent
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Address { get; set; }
        public string Town { get; set; }
        public string Password { get; set; }
    }
    
    
    public class PasswordRequiredParent : IParent
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Address { get; set; }
        public string Town { get; set; }
        [Required]
        public string Password { get; set; }
    }