Where should ASP.NET MVC 2 validation go: in the model or viewmodel classes?

有些话、适合烂在心里 提交于 2019-12-03 14:40:44

Validation should be done minimum at the View Model because this is what you receive as action argument and contains the user input. You could also have validation at the model.

My answer would be ViewModel because Model can change (for example from using Linq2SQL to EF). This way when you plug another Model you still have your validation intact.

I personally have my validation 2 places using DataAnnotations. My model is not passed up to my view in full. I have separate models for my views and translate the data from the view model into the model. This way, I can put whatever I want in my view model and leave out the pieces I don't want to deal with.

My reasoning, however, is that I have a windows application and an web application using the same model. This way, the same set of validation rules govern the Model for all apps, and my view model can have slightly different rules if need be. Of course, this creates a "duplication of logic" - well, validation logic.

This way I don't have to rebuild the data that wasn't used on the page every trip back to the server or put it in hidden fields and inflate the size of my pages.

You should put validation that is specific to the UI in the ViewModel, and anything that is related to business process or database validation in the Model. These might overlap.

The model should implement the validation it needs to ensure that its state cannot become invalid; that validation most definitely belongs on the model. for example, a book class must guarantee that its title must be between 1 and 50 characters, its id must be >= 0 etc.

business rules belong elsewhere (in your controllers if you only have the model view and controller layers). this might be something like a user cannot add more than 3 books if their email isnt verified.

validation in the view should be restricted to parsing user input for invalid data: anti xss, sql injection, out of range. etc

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