【发布时间】: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