基于其他字段的验证?
在 ASP.NET MVC 2 中,我有一个包含一系列字段的 Linq to sql 类。现在,当另一个字段具有特定(枚举)值时,其中一个字段是必需的。
到目前为止,我编写了一个自定义验证属性,它可以将枚举作为属性,但我不能说,例如: EnumValue = this.OtherField
我应该怎么做?
In ASP.NET MVC 2, I have a Linq to sql class that contains a series of fields. Now I one of the fields is required when another field has a certain (enum) value.
I've come so far that I wrote a custom validation attribute, which can take an enum as an attribute, but I can't say, for example: EnumValue = this.OtherField
How should I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MVC2 附带了一个示例“PropertiesMustMatchAttribute”,它展示了如何让 DataAnnotations 为您工作,并且它应该在 .NET 3.5 和 .NET 4.0 中工作。该示例代码如下所示:
当您使用该属性时,不是将其放在模型类的属性上,而是将其放在类本身上:
当在自定义属性上调用“IsValid”时,将传递整个模型实例这样您就可以通过这种方式获取依赖属性值。您可以轻松地遵循此模式来创建更通用的比较属性。
MVC2 comes with a sample "PropertiesMustMatchAttribute" that shows how to get DataAnnotations to work for you and it should work in both .NET 3.5 and .NET 4.0. That sample code looks like this:
When you use that attribute, rather than put it on a property of your model class, you put it on the class itself:
When "IsValid" gets called on your custom attribute, the whole model instance is passed to it so you can get the dependent property values that way. You could easily follow this pattern to create even a more general comparison attribute.