MVC Validation using Data Annotations - Model clas

2019-03-25 14:38发布

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.

4条回答
等我变得足够好
2楼-- · 2019-03-25 15:23

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楼-- · 2019-03-25 15:26

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楼-- · 2019-03-25 15:34

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

查看更多
Viruses.
5楼-- · 2019-03-25 15:38

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.

查看更多
登录 后发表回答