I have a couple model classes like so:
public class MyModelBase { public string Name { get; set; } } public class MyModel : MyModelBase { public string SomeOtherProperty { get; set; } }
How can MyModel add a [Required] attribute to the Name property?
The default is false (single-use). The parameter inherited (optional) provides value for the Inherited property of this attribute, a Boolean value. If it is true, the attribute is inherited by derived classes.
Subclasses can have two kinds of attributes: local and inherited. A local attribute is one that is defined on the subclass. An inherited attribute is one that is inherited from a parent product class. You customize an inherited attribute domain by editing its definition at the subclass level.
Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element.
Declare the property in the parent class as virtual:
public class MyModelBase { public virtual string Name { get; set; } } public class MyModel : MyModelBase { [Required] public override string Name { get; set; } public string SomeOtherProperty { get; set; } }
Or you could use a MetadataType to handle the validation (as long as you're talking about DataAnnotations...otherwise you're stuck with the example above):
class MyModelMetadata { [Required] public string Name { get; set; } public string SomeOtherProperty { get; set; } } [MetadataType(typeof(MyModelMetadata))] public class MyModel : MyModelBase { public string SomeOtherProperty { get; set; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With