具有服务器端验证的 MVC2 DataAnnotations

发布于 08-27 20:16 字数 159 浏览 12 评论 0原文

如何在不使用 MVC 库的情况下验证包含 DataAnnotations 的实体?当您在表示层中时,使用 Model.IsValid 没问题,但是当您想确保模型在域/业务层中有效时该怎么办?我是否需要一个单独的验证框架,或者我是否缺少一种简单的方法?

感谢您的帮助,

马克

How do you validate an entity containing DataAnnotations without using the MVC library? Using Model.IsValid is fine when you're within the Presentation layer, but what about when you want to ensure the model is valid in the Domain/Business layer? Do I need a separate validation framework, or is there an easy way I'm missing?

Thanks for any help,

Mark

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

好久不见√2024-09-03 20:16:48

我想你的意思是 ModelState.IsValid by Model.IsValid,对吧?好吧,DataAnnotions 根本不依赖于 MVC,因此您始终可以使用 IValidatableObject 接口。

或者验证器类可能更合适,通过使用 Validator.ValidateObject(object, ValidationContext)

I suppose you mean ModelState.IsValid by Model.IsValid, right? Well, DataAnnotions don't depend on MVC at all, so you can always use the IValidatableObject interface.

Or perhaps the Validator class will be more appropriate, by using Validator.ValidateObject(object, ValidationContext).

辞取2024-09-03 20:16:48

我使用纯 C# 编写了验证逻辑,我的业务层包含这些验证,并且我在整个业务层中使用 try 和 catch 块。表示层捕获这些自定义异常,以便将错误显示在屏幕上给用户。我只在数据注释中保留基本验证,例如 [Required] 主要用于 ajax 调用并通知用户在不可为空的字段中输入数据,这样我的业务逻辑保留在我的中间层,它保持一致,它只保留在一个地方我可以参考一下。

I wrote my validation logic using plain c#, my business layer contains these validations and I use try and catch blocks throughout business layer. The presentation layer catches these custom exceptions so errors are shown on screen to the user. I only kept basic validation inside the data annotations e.g. [Required] mainly for ajax calls and to notify users to enter data in non nullable fields, that way my business logic remained in my middle tier, it remained consistent, it remained in only one place which I can refer to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文