为什么继承的数据注释停止工作?

时间:2015-02-04 13:06:32

标签: c# asp.net-mvc-5 data-annotations

如果有人错过了标签:我正在使用.NET MVC5开发Web应用程序,并使用数据注释进行验证(客户端和服务器端)。

我想自定义内置注释(Required,StringLentgth,Range等)以更好地满足我的需求。我开始创建自己的继承RequiredAttribute的类,几乎没有添加任何内容,并使用Required替换了我的viewmodel上的Test。我跑了,期待它像以前一样100%工作,但令我惊讶的是,验证停止了完全为该字段工作。在HTML中,以前的data-val-required="......"根本就没有显示出来。

我的新属性(我已尝试使用或不使用规范,结果相同):

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class TestAttribute : RequiredAttribute
{
    // Literally nothing new, same as superclass.
}

viewmodel中的带注释的属性:

// Before, works.
[Required]
public int WorkerId { get; set; }

// After, doesn't work.
[Test]
public int WorkerId { get; set; }

那么,这是如何工作的?为什么简单地通过子类化来改变行为?我应该如何继承属性来继承他们的行为?这不违反Liskov替代原则吗?

2 个答案:

答案 0 :(得分:3)

我希望服务器端验证继续工作,但客户端验证停止工作的原因是你必须告诉ASP.NET使用哪个适配器来生成客户端验证JavaScript。如果您实际上没有更改RequiredAttribute的行为,则可以使用其适配器。将以下代码放在Application_Start()方法中。

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(Test), typeof(RequiredAttributeAdapter));

答案 1 :(得分:1)

[更新:AS Davor在评论中指出。这是错误的!!回答。只是把这个留给任何人都会遇到同样的问题。抱歉。 ]

MSDN中引用的Required属性是不可继承的。 https://msdn.microsoft.com/en-us/library/microsoft.build.framework.requiredattribute(v=vs.110).aspx

  [AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = false, 
	Inherited = false)]

  public sealed class RequiredAttribute : Attribute

相关问题