2

As discussed throughout the various MVC questions and blogposts, we know that the ASP.NET MVC project layout is heavy on convention.

I blindly made a sub-directory in the Controllers folder.

This doesn't feel right.

alt text http://www.imagechicken.com/uploads/1252003002097179400.png

Question: What's the common accepted convention on which directory to store your ViewModels? What are your suggestions or what is the established convention?

Community
  • 1
  • 1
p.campbell
  • 98,673
  • 67
  • 256
  • 322

3 Answers3

11

I use a "Models" folder alongside Controllers and Views. The same one which is empty in your project (I don't use Areas).

The "M" in "MVC" model goes in a separate assembly. The only models in the web assembly are presentation/edit models.

Inside the Models folder, there are subfolders by namespace as usual. So I have:

Vertex.Data (Assembly with repositories, etc.)

Vertex.Web

Controllers
  BarController
  FooController
Models
  Bar
    BarListItem
  Foo
    FooDetail
    FooListItem
Views
  Bar
  Foo
  Shared

...etc.

Community
  • 1
  • 1
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
7

I typically create a model for every view. Even if it is just an exact map of some other object in my project that I could be using. This way my view and it's required model is decoupled from the rest of the application. It also makes adding data to the view in the future very easy by just extending your view's model.

It takes a little more work up front and sometimes seems like your duplicating objects but I just prefer the seperation.

I store all my view models in the models directory created in an MVC project. Those 'models' map one to one to my views. I use subfolders within the Models folder if the view models become more than just basic data holders. The subfolders would contain all the bits and pieces required to represent that view.

Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • This is pretty much exactly how I've come to think about view models. There's nothing wrong with sharing models between views but there's also nothing wrong with every view having its own model.Following this approach, you could extend Craig's folder structure such that in each Models/{Controller} folder there would be a folder for each action. In that folder you would put the main model for the action and any needed sub-models. – Sean Apr 20 '13 at 00:35
5

I think the idea is that (View)Models should go in the Models directory (which is empty when you create a new ASP.NET MVC project).

Personally, it makes more sense for me to arrange namespaces around features instead of mechanics, but while this is of no consequence with regards to Models, it would have some implications when it comes to Controllers and Views.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736