Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Organizing controllers and views in subfolders - best practice

I am thinking through the best practice for organizing my code in an ASP.NET Core MVC app. I have two types of users, Doctors and Nurses, would it be best practice to organize all my Doctors and Nurses controllers/views in its own Doctors and Nurses sub folders within the controllers/views folder?

Controllers:

  • Controllers/Doctors/HomeController.cs
  • Controllers/Nurses/HomeController.cs

Views:

  • Views/Doctors/Home/Index.cshtml & other View files
  • Views/Nurses/Home/Index.cshtml & other View files

The reason for this is because at each of the Doctors/Nurses sub folder level I want to have its own shared folder for a _viewstart file.

  1. Is there a better best practice for this situation?
  2. Also, within my controllers, how do I get to the subfolder level View files? The only way that I have found is to explicitly specify them:
public string Index()
{
    return View("~/Views/Doctors/Home/Index.cshtml");
}
  1. If I want my default route to go to the Doctors/HomeController/Index page is this how I specify the default route in my startup.cs file. It doesn't seem to work.
app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "default",
      template: "Doctors/{controller=Home}/{action=Index}/{id?}");
});
  1. Lastly, as I had mentioned that I want to have a different _ViewStart.cshtml for each of the subfolders. Would this work/is it acceptable?
like image 611
Reza Avatar asked Dec 19 '22 17:12

Reza


2 Answers

Big Thanks to @Craig W. for suggesting Areas. Unlike in older versions of MVC, with Core there is no formal "Areas" option when you right click on the Project. You can however create a folder and name it "Areas". Within the Controllers you can decorate each controller with [Area("Doctors")] to specify the controller for within the Areas.

As far as the startup.cs, I was able to use the following:

app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "areaRoute",
      template: "{area:exists}/{controller}/{action}");


    routes.MapRoute(
      name: "default",
      template: "{area=Doctors}/{controller=Home}/{action=Index}");
});
like image 146
Reza Avatar answered Mar 06 '23 03:03

Reza


If you wish to use subfolders for your views or partials, the syntax is

public IActionResult Index()
{
    return View("~/Views/Doctors/Index.cshtml");
}
like image 40
Elvis Skensberg Avatar answered Mar 06 '23 03:03

Elvis Skensberg