Esteban
Esteban

Reputation: 3139

MVC Areas: How should I map my routes?

I wanted to organize my solution and I looked into areas but it seems the: The request for 'ControllerName' has found the following matching controllers... error is getting famous.

I added an Admin area and my project's folder structure looks like this:

On my AdminAreaRegistration file I have this:

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

And I'm doing this when registering my routes:

routes.MapRoute(
    "Home", 
    "Home/Index", 
    new { controller = "Home", action = "Index" }
);

I've read here to do this on my Application_Start method:

ControllerBuilder.Current.DefaultNamespaces.Add("X.Web.Controllers");

Sadly it didn't fix the error. Then I read here to add the namespace of the default (root) controller is in, in the RegisterRoutes method.

I know areas is all about routing, the folders are merely needed, but they're useful though.

I would like to know how can I map my routes to a specific HomeController in this case, one is in X.Web.Controllers and the other one is in X.Web.Areas.Admin.Controllers. Plus I would like to know if the links can be generated with an @Html.RouteLink helper instead of ActionLink, because in all the examples I've read so far the links are being generated using the ActionLink method... which makes me doubt.

I'll appreciate any help/guidance provided. Thanks.

Upvotes: 1

Views: 865

Answers (1)

Chris
Chris

Reputation: 12282

I've stumbled upon a similar problem, and as I couldn't find a 'clean' solution, I ended up renaming one of the HomeControllers - that should help.

As for the links - yes it is possible to generate them, you need to add the area name to one of the parameters (routeValues), so:

@Html.ActionLink("link text", "ActionName", "ControllerName", new { area = "Admin" })

Upvotes: 1

Related Questions