将数据注释验证与复杂的业务规则相结合
我了解用基本的必需长度和最小长度注释类属性,并获得 asp.net mvc 服务器端和客户端验证的所有好处。
但是,是否有人有一个链接,显示如何将此“基本”验证与更复杂的业务规则结合起来。我将如何运行业务规则功能,例如客户在去年订购了任何东西(需要数据库命中)并且仍然使用相同的 DataAnnotation 和 mvc 验证管道?
目标:不想要两种生成和输出验证方法的方法。
I understand annotating class properties with the basic required and minimum length and getting all the benefits of the asp.net mvc server side and client side validation.
However does anyone have a link that shows how you combine this 'base' validation with more complex business rules. How would I run business rule functions, such as for example, has the customer ordered anything in the last year (database hit required) and still use the same DataAnnotation and mvc validation plumbing?
Goal : Don't want two ways of generating and outputting validation methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
数据注释在调用您的操作之前运行。然后,无论验证是否成功,该操作仍然会被调用。如果 DA 检测到无效数据,您的 ModelState 将无效。
到达此处后,如果您愿意,您仍然可以对业务规则进行任何所需的验证,就像通常在没有数据注释的情况下所做的那样。在您的操作中,即使数据注释验证通过,您也可以将错误添加到 ModelState。
在这种情况下,您可以使用 ModelState.addError 添加错误,并且这些错误将添加到 DA 提供的任何错误中。因此,在您的视图中,错误来自何处并不重要。
或者,如果您的规则是通用的,您可以编写自己的注释标签。数据注释事物与其源一起分发,因此您可以完全控制它。
Data Annotation run before your action is invoked. Then, regardless whether the validation succeded or not, the action is still called. If the DA detected invalid data, your ModelState will be invalid.
Once here, you can still do any validation you want, for your business rules, as you would normally do without the data annotation, if you want to. In your action, you can add errors to the ModelState even if the Data Annotation validation passed.
In this case, you add your errors with ModelState.addError, and those errors are added to any error provided by the DA. So in your View it doesn't matter where the error comes from.
Or, if your rules are general, you can write your own annotation tags. The Data Annotation thing is distributed with its source, so you have full control on it.
您可以使用 Microsoft Enterprise Library 5 中的 VAB(应用程序验证块),它实际上基于 DataAnnotations 类,但您可以通过配置轻松完成复杂的业务逻辑...
我建议你检查一下...
You could use VAB (Application Validation Block) from the Enterprise Library 5 of Microsoft that actually based on the DataAnnotations class but u do your complex bussiness logic very easily through configuration...
i'd suggest you check it out...
看一下下面的文章,您可以在同一字段上多次使用 DataAnnotations,比较 N 个属性和 N 个值......
http://www.codeproject.com/KB/validation/MultipleDataAnnotations.aspx
Have a look at following article, where you can use DataAnnotations Multiple Times On Same Field, Compare N number of properties and N number of values....
http://www.codeproject.com/KB/validation/MultipleDataAnnotations.aspx
来自 http://msdn.microsoft.com/en -us/library/dd901590%28VS.95%29.aspx:
那里似乎有示例代码。
From http://msdn.microsoft.com/en-us/library/dd901590%28VS.95%29.aspx:
There appears to be example code there.