派生类的C#验证属性

时间:2019-02-12 18:32:28

标签: c# .net asp.net-mvc validation attributes

我有一个具有某些属性的基类:

public class A
{
   [Display(Name = "Some Property")]
   public virtual int SomeProperty {get;set;}
}

及其派生类:

public class B:A
{
   [Required]
   public override int SomeProperty {get;set;}
}

但是实际上,当我将类B的元数据提取到ModelMetadata时,IsRequired属性设置为false。有没有一种方法可以应用Required属性,因此它反映在ModelMetadata中?

1 个答案:

答案 0 :(得分:0)

请尝试以下示例:

public class A
{
    [Display(Name = "Some Property")]
    public virtual int SomeProperty { get; set; }
}
public class B : A
{
    [MyRequired]
    public override int SomeProperty { get; set; }
}

[AttributeUsage(AttributeTargets.Property, Inherited = true)]

public class MyRequiredAttribute : RequiredAttribute
{

}

最后:

test of code

相关问题