Introduction
When we work with ASP.NET MVC, we find some default folders (view, model, controller, and some more), but if the application is big, it is complicated to maintain a structure logic for the files and modules for the site. To solve this problem, ASP.NET MVC provides a powerful feature called areas, with areas it is possible to "isolate" the modules of your site.
Using the code
First step: create a new ASP.NET MVC 4 application, I recommend to use the basic template.
Next step: Over the project name, right click -> Add -> Area, and assign a name to the new area, when the area creation ends, we see a new folder called Areas, and within this folder you can see a folder with the name of your area and some files, think that an area is a mini-MVC project within your principal project.
The next image shows how it looks if you create an area called Reportes
:
An important file that is created too, is ReportesAreaRegistration.cs, this file is used to configure the routing system for the area.
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Reportes_default",
"Reportes/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
Also, in Global.asax, on the Application_Start
method the configuration for the areas is called:
AreaRegistration.RegisterAllAreas();
Now, if you run the application, you received an error that says:
The request for ‘Home’ has found the following matching controllers:
Areas.Areas.Reportes.Controllers.HomeController
Areas.Controllers.HomeController
This error is produced because you have two controllers with the same name, but the solution is easy, go to the function RegisterRoutes
of the class RouteConfig
and add a namespace:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Areas.Controllers" }
);
I hope this post will be useful for you!