使用MVC验证数据注释 - Model类或视图模型类的? [英] MVC Validation using Data Annotations - Model classes or View Model classes?

查看:95
本文介绍了使用MVC验证数据注释 - Model类或视图模型类的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是不是把数据验证注解在模型或视图模型的最佳实践?有什么优势/过另一种方式的缺点是什么?

Is it best practice to put data validation annotations in the Model or View Model? What are the advantages/disadvantages of one approach over the other?

好奇,看看大家都在把自己的验证,我目前做的样板工程。不过,我已经看到了一些人说这是不是最好的做法。

Curious to see where everyone is putting their validation, I am currently doing it in the model project. However I have seen a few people say this is not best practice.

推荐答案

至于最佳实践而言,我会说:都没有的。验证应该是分开的。框架如 FluentValidation 允许您在验证逻辑从模型完全分离。但是,为了回答你的问题,我会把验证到视图模型作为那些是你要绑定你的控制器操作的类。你也可以有被绑定到同一型号但不同的验证规则的多个视图模型。

As far as best practices is concerned I would say: in neither of them. Validation should be separate. Frameworks such as FluentValidation allow you to completely separate your validation logic from your models. But to answer your question I would put validation into View Models as those are the classes you are binding your controller actions to. You could also have multiple View Models that are tied to the same model but with different validation rules.

这篇关于使用MVC验证数据注释 - Model类或视图模型类的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆