3
votes

I'm having trouble getting nested areas to work.

I would like to use a structure within the Areas folder, to organize my areas. I.e.:

  • Areas
    • Admin
      • Index (Default)
      • Locations
        • Controllers
        • Models
        • Views
      • ...
    • Applications
      • Index (Default)
      • Calendar
        • Controllers
        • Models
        • Views
      • ...
    • ...

How do I go about structuring that with routes and how do I register each area. "Admin" and "Applications" are what I would call sections, and then the actual areas are located within a section.

I would have preferred using a route with an extra element, section, like so:

routes.MapRoute(
    "Applications_default",
    "{section}/{area}/{controller}/{action}/{id}",
    new { section = "Applications", area = "Index", action = "Index", controller = "Home", id = UrlParameter.Optional }
);

Would that be possible?

I think I'm missing something with routes, because adding the route is one thing, but what would I name the area (AreaName property)? "Admin/Index"? "Admin.Index"? "Index" could be used in other places..

For now I'm trying the "normal" area registration using:

public override void RegisterArea(AreaRegistrationContext context) {
context.MapRoute(
    "Admin_Index_default",
    "Admin/Index/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

}

But when I go to http://localhost:60864/Admin/Index/Home/Index I get an error saying: "The resource cannot be found." :(

How do I structure my routes to comply with my desired tree structure? I looked at another question: Can I nest areas in ASP.NET MVC?, but it did not solve my problem :(

Any help and guidance would be appreciated!

Thanks in advance

2

2 Answers

3
votes

You should not restructure or reorganize your Areas folder. Keep the default, where each area has a Controllers, Models, and Views folder (plus AreaRegistration.cs, etc). Otherwise, you may be dealing with a spiderweb of namespace problems. Also, you will have to tell the razor engine which folders to check to find your views. Trust me your life will be happier if you just follow the conventions when it comes to areas.

If you want to create a deep URL structure, do it with routes. Your routes can be completely independent of your folder structure in MVC (unlike in webforms).

Do you try this route with a fresh MVC project? Meaning, no re-arrangement of the Areas folders? It should work, as long as your Admin area has a HomeController with an Index action:

public override void RegisterArea(AreaRegistrationContext context) {
    context.MapRoute(
        "Admin_Index_default",
        "Admin/Index/{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
1
votes

I don't think this is supported. For deep URLs I suggest using MvcCodeRouting, and you can forget about routing issues.