user2062383
user2062383

Reputation: 959

Do viewModels belong in the Web Layer or Service Layer?

My application currently follows a service pattern, where the models are thin and mvc-blind, and the controllers call Services that retrieve data from the model.

Right now my controllers construct and consume ViewModels based on the data that they get from the Services or Client.

What I'm wondering is - would it be wise to relocate the ViewModel classes to the service layer?

Before:

  1. Controller asks service for data
  2. Controller accepts data and constructs viewModel
  3. Controller sends viewModel to client
  4. Client sends data back to Controller
  5. Controller takes data from viewModel and sends it back to Service to update db

After

  1. Controller asks service for data
  2. Service constructs a viewModel and populates it with data
  3. Controller accepts viewModel
  4. Controller sends viewModel to client
  5. Client sends data back to Controller
  6. Controller forwards viewModel to Service
  7. Service pulls data apart and performs updates/queries as needed

Is one better than the other? Why?

Upvotes: 0

Views: 495

Answers (1)

devdigital
devdigital

Reputation: 34349

Before is the better approach. Your view model should be a model of your view, as the name implies.

It may contain data retrieved by a service, but it's likely to also be augmented with additional data required for that specific view.

Also, the view model is likely to be UI technology specific, whereas the service should be completely UI agnostic. The service code is likely to be reusable across UI technologies, but the view model code is likely not to be.

In fact in a fat client application, your view models are likely to be more than just data transfer objects, but will also contain presentation logic as well as manage user state etc. Your service code will most likely not be tied to a specific client implementation.

Upvotes: 3

Related Questions