Fetching data within an ASP.NET MVC ViewModel class?

前端 未结 6 1108
清歌不尽
清歌不尽 2021-01-30 18:36

For those that create ViewModels (for use by typed views) in ASP.NET MVC, do you prefer to fetch the data from a service/repository from within the ViewModel, or the controller

6条回答
  •  梦毁少年i
    2021-01-30 19:33

    Consider passing your services into the custom ViewModel on its constructor (ala Dependency Injection). That removes the model population code from your controller and allows it to focus on controlling the logical flow of the application. Custom ViewModels are an ideal place to abstract the preparation of things like SelectLists that your droplists will depend on.

    Lots of code in the controller for things like retrieving data isn't considered a best practice. The controller's primary responsibility is to "control" the flow of the application.

提交回复
热议问题