Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Data Annotations to Inherited Class

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?

like image 933
Pete Avatar asked Feb 07 '14 09:02

Pete


1 Answers

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.

like image 102
Sameer Avatar answered Nov 06 '22 07:11

Sameer