.Net

Difference between 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.

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 model helps us in creating, editing, updating, deleting operation in our application.

Example:

Let we consider StudentDetails which was created using Entity Framework.

public class StudentDetails 
{
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName{ get; set; }
public string Address { get; set; }
public int Age { get; set; }
public Course CourseId{ get; set; }
}

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 StudentId, FirstName, CourseId. So we are going to remove the unwanted details in our model, based on the UI requirement as shown below.

public class StudentDetails 
{
public int StudentId{ get; set; }
public string FirstName { get; set; }
public Course CourseId{ get; set; }
}
  • 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.

Model – any business object, this is a kinda broad term. It can be an entity, some custom class you’ve created in your project etc.. It’s pretty much everything that isn’t a view nor a controller/viewmodel.

ViewModel – some kind of a mediator between a model and the view. It modulates the communication between the model and the view, for instance applies validation, combines more models into one bigger object etc., for the purposes of the interaction with the specific view. ViewModel is also responsible for event handling (button mouse clicks for instance), so it exposes commands to the view you bind to (WPF).

Shaiv Roy

Hy Myself shaiv roy, I am a passionate blogger and love to share ideas among people, I am having good experience with laravel, vue js, react, flutter and doing website and app development work from last 7 years.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button