Alex Rivera | Logout

ViewModel Best Practices

Asked 2009-03-19T21:48:58.123
241

From this question, it looks like it makes sense to have a controller create a ViewModel that more accurately reflects the model that the view is trying to display. However, I'm curious about some of the conventions.

Basically, I had the following questions:

  1. I, normally, like to have one class/file. Does this (preference) make sense with a ViewModel if it is only being created to hand off data, from a controller to a view?
  2. If a ViewModel does belong in its own file, and you're using a directory/project structure to keep things separate, where does the ViewModel file belong? In the Controllers directory?

That's, basically, it for now. I might have a few more questions coming up, but this has been bothering me for the last hour, or so; and I can't seem to find consistent guidance, elsewhere.

EDIT: Looking at the sample NerdDinner app on CodePlex, it looks like the ViewModels are part of the Controllers, but it still makes me uncomfortable that they aren't in their own files.

Edit
Report

1 Answer

13

A ViewModel class is there to encapsulate multiple pieces of data represented by instances of classes into one easy to manage object that you can pass to your View.

It would make sense to have your ViewModel classes in their own files, in the own directory. In my projects I have a sub-folder of the Models folder called ViewModels. That's where my ViewModels (e.g. ProductViewModel.cs) live.

answered 2009-03-19T22:34:00.700

Your Answer