简体   繁体   中英

C# validation attributes for derived class

I have a base class with some properties:

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

and its derived class:

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

But in fact, when I extract metadata for class B to ModelMetadata, IsRequired property is set to false. Is there a way to apply Required attribute, so it was reflected in ModelMetadata?

Please try the example below:

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
{

}

finally:

代码测试

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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