0

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

Community
  • 1
  • 1
Thomas
  • 33,544
  • 126
  • 357
  • 626

1 Answers1

2

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):

public class Person{
    public int PersonId{get;set;}
    public string Name {get;set;}
    .
    .
    .
}
public class Address{
    public int AddressId{get;set;}
    public string Street1 {get;set;}
    public string Street2 {get;set;}
    .
    .
}

Then you can have a viewModel class like so:

public class MyViewModel{
    public Person ThePerson{get;set;}
    public Address TheAddress{get;set;]}
}

Or even

public class MyViewModel : Person{
    public Address TheAddress{get;set;]}
}

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

JTMon
  • 3,189
  • 22
  • 24
  • thanks great......can u post full code like controller...model/viewmodel and bind view with view model data. – Thomas Sep 05 '12 at 13:28
  • 1
    If you give me the full specs of the project...... and an appropriate fee... sure not a problem :) What you are asking for is way beyond the scope of a help site and if you learn how to do that with regular models (maybe through a basic Asp.net-mvc tutorial), you can do the exact same with the viewModel no difference whatsoever. – JTMon Sep 05 '12 at 13:38