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

前端 未结 4 938
心在旅途
心在旅途 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:29

    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

    0 讨论(0)
  • 2021-02-14 08:31

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-14 08:41

    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.

    0 讨论(0)
提交回复
热议问题