Say I have the following class:
public class ContactUsFormModel : AddressModel
{
[DisplayName("Title")]
[StringLength(5)]
public string Title { get; set; }
[DisplayName("First name (required)")]
[Required(ErrorMessage = "Please enter your first name")]
[StringLength(50, ErrorMessage = "Please limit your first name to {1} characters.")]
public string FirstName { get; set; }
// etc...
}
Am I able to add a required attribute to a property from the AddressModel
class in the ContactUsFormModel
class?
Try to Use MetadatatypeAttribute. Create seprate class for metadata where you directly add attributes to your properties.
[MetadataType(typeof(MyModelMetadata ))]
public class ContactUsFormModel : AddressModel
{
[DisplayName("Title")]
[StringLength(5)]
public string Title { get; set; }
[DisplayName("First name (required)")]
[Required(ErrorMessage = "Please enter your first name")]
[StringLength(50, ErrorMessage = "Please limit your first name to {1} characters.")]
public string FirstName { get; set; }
// etc...
}
internal class MyModelMetadata {
[Required]
public string SomeProperyOfModel { get; set; }
}
[Edit] Above method is not useful for you, as you said it will not add attributes to base class.
So make the properties in AddressModel virtual
and override
them in ContactUsFormModel and this way you can add attribute.
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