对于 MVC 应用程序,我的业务规则验证是否应该在视图模型和/或控制器中复制?
我的 MVC 应用程序有一个定义良好的域模型,每个模型都执行自己的业务规则检查。
我的问题是业务规则是否也应该在视图模型或控制器中复制,或者我应该只允许模型生成验证错误?
让我们假设我们正在讨论的验证无法在客户端完成,并且比简单的字段验证更复杂,可以通过将验证属性添加到视图模型属性来完成。
允许模型处理所有验证的问题在于,它生成的错误消息可能不适合其耦合到的特定视图,例如字段名称可能不正确。另外,我需要使用视图模型属性名称而不是域模型中的属性名称将错误添加到 ModelState。
将相同的业务规则验证添加到视图模型/控制器的问题是明显的重复维护问题,这意味着我的域模型中的验证实际上不应该产生任何错误,这使得它有点毫无意义。
人们通常如何处理这个问题?
My MVC application has a well defined domain Model with each Model performing its own business rule checks.
My question is should the business rules be replicated in the view model or controller too or should I just allow the model to generate the validation errors?
Lets assume that the validation we are talking about can't be done client-side and is more complicated than simple field validation that can be done by adding validation attributes to the view model properties.
The problem with allowing the model to handle all of the validation is that the error messages it generates might not be suitable for the particular view that its coupled to, field names might not be correct for example. Also I need to add the error to the ModelState using the view model property name not the property name from the domain model.
The problem with adding the same business rule validation to the viewmodel/controller is the obvious duplication maintenance issue and it means the validation in my domain model really should never produce any errors which kind of makes it a bit pointless.
How do people usually handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这种情况下通常使用的解决方案是在模型中进行验证(或者在我的情况下通常是验证库),但在控制器中添加错误,这允许您捕获标准验证错误,如下所示:
这可能不会正是您正在寻找的东西,但它可能会帮助您想出一种最大化可重用代码的方法,同时仍然能够自定义它。
我曾经这样做过 - 但我硬着头皮,我最近的应用程序到处都使用标准错误消息 - 我这样做的动机是用户越来越习惯简短的验证消息,并且消息中不需要字段名称,如果该消息与表单字段内联显示,而不是作为摘要显示。这也允许我将所有规则/消息放入数据注释中,我发现它很有效。
The solution I typically used to use in this scenario is to have the validation in the Model (or in my case typically a validation library) but add the error in the controller which allows you to catch the standard validation error like this:
This may not be exactly what you are looking for but it might help you come up with a way of maximising re-usable code whilst still being able to customise it.
I used to do it like this - but I bit the bullet and my most recent applications use standard error messages everywhere - my motivation for this is that users are increasingly comfortable with short-simple validation message and field names are not required in the message if the message is displayed inline with the form field rather than as a summary. This also allows me to put all my rules/messages in data annotations and I find that it works a treat.