MVC Validation using Data Annotations - Model classes or View Model classes?

浪尽此生 提交于 2019-12-04 18:23:55

问题


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.


回答1:


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.




回答2:


Put your Annotations in your Viewmodel.

It is possible to have multiple ViewModels for each DataModel, eg DisplayModel, EditModel, ListModel .. all which may require different annotations.

It is generally considered best practice not to expose your DataModel directly to a view, espcicially in "POST"/Edit scenarios.

I suggest reading Brad Wilson's excellent overview at: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html

These articles primarily cover the use of Dislpay and Edit templates within MVC2, but clearly illustrate the advantages of using the ViewModel pattern




回答3:


If you follow single responsibility then it should probably go into it's own component. That being said, if you want to make a short cut it's okay to but it in the ViewModel. It definitely shouldn't go in the model though. Your model should be "pure" data. No business rules and validation is business rules.




回答4:


Well my opinion is: it depends. I usually control my input in the controllers and the models, so the input is validate both in the controller and in the model. This is in case I want to tie the model to another sort of app. Say, WPF.

However, a lot of people also employ "defensive programming". This means that every input to a function (paramter) is checked. In this case one input may be checked a couple of times but you ensure that even if you change something, the validation logic holds.

So for me, a couple of questions arise:

1) Is there any chance that there can be a scenario where the validation logic is bypassed. Like tying the model to a wpf app.

2) Do I want to compromise performance over ensuring security by checking the input in every function?

For me this article on cross cutting concerns also helped.

Those are my thoughts on the matter. Hope it helps



来源:https://stackoverflow.com/questions/3338919/mvc-validation-using-data-annotations-model-classes-or-view-model-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!