I am trying understand ViewModels deeper and I have read many articles and blogs regarding ViewModel in MVC. In some articles it is said that a Model should not be referenced from ViewModel but in some other articles, using model as a member of viewmodel is suggested.
Lets take an example where I have to create a ViewModel based on a model. I could possible do this in two ways:
1
public class Car
{
public int Year {get;set;}
public string Make {get;set;}
//more properties......
}
public class CarViewModel
{
public CarViewModel(Car model)
{
Model = model;
}
public Car Model { get; set; }
//additional view model specific properties
}
Or 2.
public class Car
{
public int Year {get;set;}
public string Make {get;set;}
//more Car properties......
}
public class CarViewModel
{
public int Year {get;set;}
public string Make {get;set;}
//more Car properties......
//additional view model specific properties
}
I am just wondering which one is the correct way of creating a ViewModel. Or is there any other way of doing this altogether?
I would go for the second approach when the
Carmodel is data persistent say it’s a class created by Entity Framework. In this case I don’t want those models floating around in controllers and views. I will create a view model equivalent to what you have done and use a tool likeAutoMapperto map the properties.In the first approach the view models acts as wrapper. This you can use in cases where you want to show additional information in a view that is tied with that model. Say you have to add a couple of UI fields and definitely you should not do that in the Car model and you have to create a view model that wraps the
Carmodel and the additional UI fields.Basically View Models helps you to keep your business models clean from UI stuff and helps to avoid models that has database stuff floating in views and controllers. So you can use two approaches depend upon the scenarios.
Hope this answers your question.