Reza
Reza

Reputation: 5634

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:

Views:

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?

Upvotes: 6

Views: 8762

Answers (2)

Elvis Skensberg
Elvis Skensberg

Reputation: 149

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

public IActionResult Index()
{
    return View("~/Views/Doctors/Index.cshtml");
}

Upvotes: 6

Reza
Reza

Reputation: 5634

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}");
});

Upvotes: 8

Related Questions