Search code examples
asp.net-mvc-3viewmodelorganization

A better way to organize view models in mvc3?


In asp.net mvc3, I currently have a single file ViewModels.cs which holds all of the viewmodel classes I use. The size of the file is only at 180 lines of code at the moment and is pretty easy to manage with #regions.

However, I fear these models could begin to add up. Moreover, it seems to me that if I break each view model class into its own file I will end up with a large amount of viewmodel.cs files.

I attempted to just make a generic view model but was advised against using generic classes as view models.

What is a better way to organize these view models, or a better approach in general to view models?


Solution

  • My standard approach has been:

    • Project.Web
      • [Content]
      • [Controllers]
        • FooController.cs
      • [ViewModels]
        • FooViewModel.cs
        • BarViewModel.cs
      • [Scripts]
      • [Views]
        • [Foo]
        • [Shared]

    And , if necessary, you can add a reference to the namespace in your config file so you don't end up adding ViewModels. to every reference:

    <pages>
      <namespaces>
        <add namespace="MyProject.Web.ViewModels" />
      </namespaces>
    </pages>
    

    If that's of any help. I've also seen people break out the ViewModels / Models folder in to sub-directories based on controller, but I don't usually go to that extent (though wouldn't hurt).