【问题标题】:C# validation attributes for derived class派生类的 C# 验证属性
【发布时间】:2019-02-12 18:32:28
【问题描述】:

我有一个带有一些属性的基类:

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

【问题讨论】:

  • 你使用什么验证框架?
  • 查看此 SO topic
  • @ZakkDiaz 标准 ASP.NET MVC 验证

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


【解决方案1】:

请尝试以下示例:

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
{

}

终于:

【讨论】:

  • 如果使用RequiredAttribute 不起作用,为什么子类化RequiredAttribute 会起作用?
  • 因为你必须设置继承属性为真
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多