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

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

提交回复
热议问题