Search code examples
asp.net-mvcviewmodel

ASP.NET MVC terminology is tripping me up - why 'ViewModel'?


I'm an ASP.NET MVC newbie, but have used many Model-View-Controller frameworks previously.

I recently came across the convention of gathering up the pieces of data that your particular view needs (indeed, it's assigned to the ViewData) into a new class called (NameOfView)ViewModel.

Gathering up this data so that it's associated with the functions provided by the View/Controller interaction strikes me as a helper struct, or even closure mechanism (in the 'encapsulates a collection of variables' sense).

So why is it called 'ViewModel', given that it's neither a View or Model?

Does anyone else find the name confusing?

EDIT: What's wrong with just putting properties onto the View so that the Controller can populate them (as in other MVC frameworks)?


Solution

  • The model is a view-agnostic representation of the data. The view model is a view-specific representation of the data: it's the model as it might appear from a given viewpoint.

    Consider a model that consists of raw data points; a histogram view might then have a view model consisting of a set of buckets and totals drawn from that data.

    Logically, it's a subset or transformation of the model - it could be generated on-demand with a view-specific function and the model as its only input.

    Regarding properties on the view vs. a property bag or custom object... I'm sure someone has strong feelings on this, but personally I don't see the big difference. You're producing a view-specific representation of the model and passing it somehow; the exact mechanism doesn't seem all that important.