0

How to disable the [Required] attribute that has been set on a model property.

I tried with below code using new keyword but not working.

I also tried override keyword as well not worked.

ChildModel uses most of the properties of BaseModel that's instead of create new model file and code many similar properties I'm thinking to do something like this.

public class BaseModel
{
    [Required]
    public string Address{ get; set; }
}


public class ChildModel : BaseModel
{
    public new string Address{ get; set; }    
}

Any simple solution ?

Neo
  • 15,491
  • 59
  • 215
  • 405
  • This previous question should help you out: [https://stackoverflow.com/questions/8903838/is-it-possible-to-override-the-required-attribute-on-a-property-in-a-model?rq=1](https://stackoverflow.com/questions/8903838/is-it-possible-to-override-the-required-attribute-on-a-property-in-a-model?rq=1) – ZippyZippedUp May 31 '17 at 13:00
  • I tried but its not working :( base and derived solution. what is this `[MetadataType(typeof(Base.Metadata))]` ? any comment? – Neo May 31 '17 at 13:04
  • Have you tried @Saito's answer in [https://stackoverflow.com/questions/8903838/is-it-possible-to-override-the-required-attribute-on-a-property-in-a-model?rq=1](https://stackoverflow.com/questions/8903838/is-it-possible-to-override-the-required-attribute-on-a-property-in-a-model?rq=1) This works fine for me. – ZippyZippedUp May 31 '17 at 13:20

1 Answers1

2

Simply overriding or redeclaring using the new keyword on the property and removing the attribute does not work. The way I have always done this is like below.:

public abstract class BaseModel
{
    public abstract string Address { get; set; }
}


public class ChildModel : BaseModel
{
    [Required]
    public override string Address { get; set; }
}

public class AnotherChildModel : BaseModel
{
    //Not[Required]
    public override string Address { get; set; }
}

You can read this thread if you want to know more on how attributes of a base class are treated during inheritance.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64