Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Grouping classes around controller

In asp.net mvc (4), out of the box, views go into Views folder, and then grouped by controller in subfolders.

Controllers go into Controllers folder, (View/Edit/Input)Models go into Models folder, etc.

I do like the way views are organized. I do not, however, like breaking the rest of the MVC pieces horizontally.

My question is, what would be downsides of leaving views organization structure as it is, but group other classes by controller (i.e. by use-cases). E.g.:

/Home
  HomeController.cs
  IndexViewModel.cs
  IndexViewModelBinder.cs
/Messages
  MessagesController.cs
  MessagesApiController.cs
  MessagesViewModelBinder.cs
  MessageViewModel.cs
  MessagesListViewModel.cs
/Views
  /Home
     Index.cshtml
  /Messages
     MessagesIndex.cshtml
     MessageDetails.cshtml
like image 735
THX-1138 Avatar asked Sep 11 '12 22:09

THX-1138


2 Answers

All that matters is the arrangement of the View files because they're accessed at runtime. Everything else is compiled into the assembly so the physical location of their source files is irrelevant.

Like you I find the default arrangement a bit awkward for larger projects, so this is how I lay out my current projects:

~/
    /Areas
        /DefaultArea // I always use areas, even when there's only one, because it simplifies things when adding additional areas.
            /Controllers
                FooController.cs
            /Views
                /Foo
                    FooView.aspx // Yes, I use WebFormView. Just a matter of personal preference
                    FooEdit.aspx
                    FooModels.cs // this file contains my ViewModels

So basically, I put my ViewModel classes in the same folder as the views rather than putting all the ViewModels together (which makes less logical sense). I was tempted to put my Controllers in their views' folders, but I decided against it.

I've found no downsides to my approach so far (been using it almost 2 years now).

like image 154
Dai Avatar answered Sep 28 '22 05:09

Dai


I generally like to avoid areas where possible as it creates some issues with routing.

I think your structure is completely fine (and superior to the default MVC/Web structure of separating code based on "type" rather thank "function").

All I would suggest is that you only keep your "web" .cs files in the web DLL (e.g. Controllers, ViewModels, Binders, etc) and have the same structure in separate DLL(s) for Domain / Services / etc layers so they can be reused / tested separately if/as required.

like image 43
Tod Thomson Avatar answered Sep 28 '22 05:09

Tod Thomson