【问题标题】:Why do inherited data annotations stop working?为什么继承的数据注释停止工作?
【发布时间】:2015-02-04 23:01:51
【问题描述】:

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

我想自定义内置注释(Required、StringLentgth、Range 等)以更好地满足我的需求。我首先创建了自己的继承RequiredAttribute 的类,实际上没有添加任何内容,并将我的视图模型上的Required 替换为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; }

那么,这是如何工作的呢?行为如何仅仅通过子类化而改变?我应该如何继承属性来继承他们的行为?这不是违反里氏替换原则吗?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 这似乎是最好的方法。我想你可以对其余的内置属性做同样的事情吗?
    • 是的,如果您需要覆盖客户端验证,因为您正在更改验证逻辑,那么也可以这样做。
    • 是的,我已经有一堆客户端的自定义属性,我只是想用本地化消息编写我自己的“必需”。我刚刚将资源文件的设置添加到从RequiredAttribute 继承的新属性的构造函数中,它就像一个魅力。谢谢:D
    【解决方案2】:

    [更新:AS Davor 在评论中指出。这是一个错误!回答。只是把这个留给任何人都会遇到同样的情况。对不起。 ]

    在 MSDN 中引用为不可继承的必需属性。 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

    【讨论】:

    • 你的命名空间/类有误,就是这个:msdn.microsoft.com/en-us/library/vstudio/… 当我在 VS 中打开RequiredAttribute 时,它​​在定义中:[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes", Justification = "We want users to be able to extend this class")]。所以他们明确希望我们能够继承它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 2012-12-15
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多