ASP.NET MVC: convention for organizing ViewModels
-
21-09-2019 - |
Question
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?
Solution
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.
OTHER TIPS
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.
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.