派生类的C#验证属性

问题描述 投票:0回答:1

我有一个基类,有一些属性:

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中?

c# .net asp.net-mvc validation attributes
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.