Difference between Model/Domain Model and ViewModel in MVC

In this post, we are going to discuss about the difference between Model and ViewModel with MVC. Before that we are going to start with what is meant by model and What is the Difference between Model and ViewModel in MVC.

What is Model/Domain Model:

Domain Model represents a domain object in our application like a Entity Framwork ,SQL…(while using ORM).

The model is an object, using that we can pass the information/data to the database. The main purpose of the model is to perform operations on that and render on the view/save to the database. The modelhelps us in creating, editing, updating, deleting operation in our application.

Example:

Let we consider EmployeeDetails which was created using Entity Framework.

public class EmployeeDetails
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName{ get; set; }
public string Address { get; set; }
public int Age { get; set; }
public Department EmpDepartment { get; set; }
}

From above model, we understood domain model has created based on DB/table structure.

What is ViewModel:

MVC ViewModel is similar to ‘model’. But the major difference between ‘Model’ and ‘ViewModel’
is that view model is only used to rendering(ie., displaying information) information in views.

Why we moving to View Model?

In most of the times, our UI/page Presentation requirements are different from domain requirements. Based on the requirement, we add/remove the attribute to the domain model. Let consider, in our view we need to display only EmployeedId, FirstName, EmpDepartment. So we are going to remove the unwanted details in our model, based on the UI requirement as shown below.

public class EmployeeDetails
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public Department EmpDepartment { get; set; }
}

Note :

  • ViewModels gives us more flexibility to organize based on our requirements.
  • ViewModels help us to manage data in our applications when we need to work with complex data.
  • It gives more flexibility for managing more than one data source.