简体   繁体   English

将数据注释添加到继承的类

[英]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? 我可以从ContactUsFormModel类的AddressModel类向属性添加必需的属性吗?

Try to Use MetadatatypeAttribute . 尝试使用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. 因此,使AddressModel中的属性virtual并在ContactUsFormModel中override它们,这样您就可以添加属性。

Ok I have found a workaround to this by adding a new property to the class: 好的,我通过向类添加新属性找到了解决方法:

public bool AddressIsRequired { get; set; }

I could set this when building my model for different forms and then instead of using the normal required attribute, I made my own custom validator: 我可以在为不同形式构建模型时进行设置,然后我使用自己的自定义验证器来代替正常的required属性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public sealed class AddressRequiredAttribute : RequiredAttribute, IClientValidatable
{
    public AddressRequiredAttribute()
        : base()
    {
    }

    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        Type addresType = typeof(AddressModel);
        if (context.ObjectType == addresType || context.ObjectType.BaseType == addresType)
        {
            AddressModel baseModel = (AddressModel)context.ObjectInstance;
            if (baseModel != null && baseModel.AddressIsRequired)
            {
                return base.IsValid(value, context);
            }
        }

        return ValidationResult.Success;
    }
}

And then in my AddressModel I could mark my properties as such: 然后在我的AddressModel中,我可以这样标记我的属性:

[AddressRequired(ErrorMessage = "Please enter your Postcode")]
public string Postcode { get; set; }

I am going to leave this open if anyone is able to find a better way of doing this (ie able to just change the data-annotation without having to make a separate attribute). 如果有人能够找到更好的方法(例如,只需更改数据注释而无需创建单独的属性),我将保持开放状态。 This way of doing things also means that if you extend the labelfor helper and use the metadata to check the IsRequired flag, the properties marked with this attribute will always be marked as required (I think this could be because it inherits from the required attribute) 这种处理方式还意味着,如果扩展标签帮助程序并使用元数据检查IsRequired标志,则带有此属性标记的属性将始终被标记为必需(我认为这可能是因为它继承自required属性)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM