[asp.net-mvc] What is ViewModel in MVC?

A lot of big examples, let me explain in clear and crispy way.

ViewModel = Model that is created to serve the view.

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.

View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.

Few examples of View Models are below

  • To list data from more than entities in a view page – we can create a View model and have properties of all the entities for which we want to list data. Join those database entities and set View model properties and return to the View to show data of different entities in one tabular form
  • View model may define only specific fields of a single entity that is required for the View.

ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.

The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.

Here is a small example of List data using ViewModel.

Hope this will be useful.