How to organize views and controllers hierarchically when having model with many children
-
22-08-2019 - |
Question
Lets say I've a website that lists Persons, and each Person has multiple properties, some one-to-one (name, address), some one-to-many (favorite colors, bank-accounts etc).
In my business layer it's nicely hierarchically organized.
How do I organize this is my controllers and views? Should I have a PersonsController, FavoriteColorsController etc? all residing in the same namespace and folder? Or should I have ony a PersonsController with many actions, such as IndexFavouriteColors, UpdateFavoriteColor etc. Both of the options are not quite it. The first one doesn't show that FavoriteColors is a child of Person and can only be used in the context of a person. The second one will create a huge PersonController.
The same thing with the views of course. The nicest would be to have
- Views/Persons/index.aspx
- Views/Persons/details.aspx
- Views/Persons/ etc.
- Views/Persons/FavoriteColors/index.aspx
- Views/Persons/FavoriteColors/details.aspx
In this example I gave only a few one-to-many properties to the Person, but actually there are many (10+), so that increases the need for clarity.
Thanks.
Solution
Actually I found the answer in "Areas", which is supposedly supported by Rails, but not by MVC, though there are private implementations:
Grouping Controllers with ASP.NET MVC
Creating MVC "Areas" as Subfolders under Views
OTHER TIPS
PersonsController.cs
public ActionResult Index()
{
return View();
}
public ActionResult Details()
{
return View();
}
public ActionResult Info()
{
return View();
}
....
Right click in each methods and generate views
In Views folder in a result you should have
Views
----- Persons
-------------Index
-------------Details
-------------Info
-------------....