Possible Duplicate:
ASP.NET MVC ViewModel Pattern
i am new in ASP.Net MVC. i saw people talk about ViewModel usage in asp.net mvc but things is actually not clear to me why i should create ViewModel classes.
it would be better if some one shed some light on the real life use of ViewModel and also explain with simple code for ViewModel. thanks
ViewModels are great for when your model entities do not correspond one to one with what you want to show on the screen.
A simple example is an application that stores information about people. Imagine your domain model has a Person entity and an address entity. Each person has many addresses but one default address. In one of your views you want to show the Person’s details as well as the details of their default address. If you want to keep your views strongly typed against a model (which you should) that would be impossible as you can not type a view to 2 entities.
Here is where viewModels are at their best. You create a new viewmodel class that has 2 properties one of type person and one of type address and in your controller you fill those properties with the needed information and you type your view against this Person+address model class.
As for the code for them they are just like any other model. An example is coming shortly.
Domain Models (found in your data access layer maybe, or in a seperate domain model project):
Then you can have a viewModel class like so:
Or even
But I prefer the first solution while a colleague chooses the second one regularly. Your views would then be strongly typed against MyViewModel and the values accessed in the view through syntax like: @model.Person.PersonId