List data using ViewModel in ASP.NET MVC

How to list data from more than one tables (models) in ASP.NET MVC?

ViewModel

ViewModel is a class that represents only the data that we want to display on the view. ViewModel can be used in read only view or in the input form page. Generally these data are combinations of more than one database tables.

ViewModel only contains the properties, so you can say that ViewModel can contain only those properties from more than one Models that we need to display or use in a single view page.

How to create and use ViewModel?

Creation of View model is similar to the creation of Model. Right click Models folder and go to Add > Class…

Give some meaningful name. It is suggested to suffix the name of View mode to “ViewModel” word so that it is can be easily distinguished in the Model folder among other Models. In our case, the View model name is PersonaldetailsFilesViewModel.cs as we are getting properties of from both PersonalDetails and Files entities (database tables).

In this method, we are first joining PersonalDetails and Files entities and creating a collection of Anonymous type collection and then converting them into the collection of PersonaldetailsFilesViewModel, that intern is being passed to the View.

Select appropriate Template, Model class and Data context and press Add button from as displayed in above picture. This creates a normal view of List type that lists the data from PersonaldetailsFilesViewModel view model. The view looks like below.