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

前端 未结 4 922
心在旅途
心在旅途 2021-02-14 07:41

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 w

4条回答
  •  盖世英雄少女心
    2021-02-14 08:39

    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

提交回复
热议问题