向继承类添加数据注释

时间:2014-02-07 09:43:07

标签: c# data-annotations

说我有以下课程:

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...
}

我是否可以从AddressModel类中的ContactUsFormModel类向属性添加必需属性?

2 个答案:

答案 0 :(得分:5)

尝试使用MetadatatypeAttribute。为元数据创建seprate类,直接向属性添加属性。

[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; }
}

<强> [编辑] 上面的方法对你没用,因为你说它不会向基类添加属性。

因此,在ContactUsFormModel中使用AddressModel virtualoverride中的属性,这样就可以添加属性。

答案 1 :(得分:0)

好的,我已经通过在类中添加一个新属性找到了解决方法:

public bool AddressIsRequired { get; set; }

我可以在为不同的表单构建模型时设置它,然后使用正常的必需属性,而不是使用正常的自定义验证器:

[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;
    }
}

然后在我的AddressModel中,我可以标记我的属性:

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

如果有人能够找到更好的方法(即能够只更改数据注释而不必创建单独的属性),我将保持开放状态。这种做法也意味着如果你扩展label for helper并使用元数据来检查IsRequired标志,那么用这个属性标记的属性将始终被标记为必需(我认为这可能是因为它继承了所需的属性)

相关问题