3

In researching MVC 3 archetectures, one thing I've seen consistently is the concept of breaking the models out into their own project and calling it ViewModels.

As I'm coding, I'm having a hard time realizing what the benefit of this is. Could someone explain what the advantages of this are?

Scottie
  • 10,410
  • 17
  • 62
  • 103

4 Answers4

5

I'm not sure where you go thid idea that View models should be in their own project. That's typically not how it's done.

Often the business model is in a seperate project, as is the data model, but the view models are typically in the web project where they belong, since they're a part of the presentation layer.

Erik Funkenbusch
  • 90,480
  • 27
  • 178
  • 274
2

Because one major thing about MVC is seperation of concern. You should create a ViewModel that has only the data your View needs, no logic.

You can, but you don't need, a seperate project (for example: a Data Access Layer)

A ViewModel is just a simple POCO class (Plain Old CLR Object, a class that only has properties, no logic)

More Information

Community
  • 1
  • 1
dknaack
  • 56,707
  • 23
  • 140
  • 187
  • Right, but why put this in a whole seperate project instead of leaving it in the MVC app? – Scottie Jan 16 '12 at 17:12
  • No, you dont need a seperate project. You should load you data and asign it to a simple class with the data your view needs. – dknaack Jan 16 '12 at 17:13
  • This looks like a good start: http://www.rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applications. Perhaps right for some situations, not for all, though. Actually, that's good enough to be an answer. – MrBoJangles Jan 16 '12 at 17:28
  • @MrBoJangles Thanks, my answer is extended – dknaack Jan 16 '12 at 17:29
1

ViewModels are used to tailor a Model for the use of a particular View. When you want to pass specific information to the View, or retrieve particular information, then you would construct a ViewModel.

An example of a ViewModel would be:

public class PersonViewModel
{
    public Person NewPerson { get ; set ; }
    public Address NewAddress { get ; set ; }
    public SelectList Suffixes { get ; set ; }
}

If you had a view that created a new person, you could pass it this ViewModel class that is designed soley for the purpose of a new person View.

  • Right, but why put this in a whole seperate project instead of leaving it in the MVC app? – Scottie Jan 16 '12 at 17:12
  • @Scottie you could separate your ViewModels if you like. That is personal preference and structure of the application. Like your Controllers, Models, and Views, ViewModels can exist inside of the MVC project. –  Jan 16 '12 at 17:13
1

View models are a part of the UI layer so they should generally stay in the same project.

Dmitry S.
  • 7,889
  • 2
  • 34
  • 49