views:

535

answers:

3

I'm basing this question on Fowler PoEAA. Given your familiarity with this text, aren't the ViewModels used in ASP.NET MVC the same as DTOs? Why or why not? Thank you.

+3  A: 

The purpose is different:

  • DTO's are used to transfer data
  • ViewModels are used to show data to an end user.

So normally ViewModels contain the presentation data, witch is in a lot of cases similar to what is in a DTO, but with some differences. Think of representation of enums, localization, currency, date formats, ... . This is because normally there should be no logic in your view.

Bavo
+12  A: 

They serve a similar purpose (marshalling data for another layer of the application) but they do it differently and for different reasons.

The purpose of a DTO is generally to reduce the number of calls between tiers of the application, especially when those calls are expensive. The purpose of a ViewModel is mainly separation of concerns - decoupling the View from the implementation details of the Model.

DTO's don't have any behaviour. ViewModels often contain logic pushed back from the view, and (especially in ASP.NET MVC) behaviour to help out with pushing data back to the Model on a user's response.

DTO's are serializable. ViewModels are not necessarily.

Iain Galloway
That's an excellent explanation! Up until now the only view models I had seen only had getters and setters so I was like: wow that's so much like a DTO. Thanks for clearing this up for me.
mkelley33
Great explanation.
Guy
+3  A: 

DTOs in MVVM and MVP are usually Very Dumb Objects and are basically just a bunch of property setters and getters. ViewModels on the other hand can have some behaviour.

A practical positive side effect of having DTOs is allow easier serialization. If you have a rather complex object in, say C#, you will often find yourself having to selectively turn things off that you don't want serialized. This can get rather ugly and DTOs simplify this process.

Igor Zevaka
+1, the key difference is that DTOs are stupid (and thus trivially serializable, which is their *job*), and ViewModels can contain logic that would have otherwise gone into your view (which is *their* job).
Iain Galloway