Liming
Liming

Reputation: 1661

Html.ActionLink generates the wrong link based on routes.MapRoute

I guess I still don't understand routing.

I have three controllers

For Dashboard, I want the url to be /Dashboard/. For Admin section, however, I want two different controllers. /Admin/Overview should be using AdminController, and /Admin/ProjectGroups/ should be using ProjectGroupsController.

This is how my routing looks like

 routes.MapRoute(
          name: "AdminOverivew",
           url: "Admin/Overview",
           defaults: new { controller = "Admin", action = "Overview" },
           namespaces: new[] { "Com.Controllers" }
        );

    routes.MapRoute(
      name: "AdminSubs",
       url: "Admin/{controller}/{action}/{id}",
       defaults: new { action = "Index", id = UrlParameter.Optional },
       namespaces: new[] { "Com.Controllers" }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional },
        namespaces: new[] {"Com.Controllers"}
    );

*Note, the reason for the 2nd route is because I have many more controllers under admin section.

It's working.. except, the URL that HTML.ActionLink generates is wrong. @Html.ActionLink("Dashboard", "Index", "Dashboard"........) generates /Admin/Dashboard when it should be /Dashboard.

However, @Html.ActionLink("Project Groups", "Index", "ProjecGroups".....) generates the correct url /Admin/ProjectGroups

If I take out the 2nd routes.MapRoute (AdminSubs), then the situation is reversed. Dashboard gets the right url, /Dashboard then Project Groups becomes /ProjectGroups when it should remain /Admin/ProjectGroups

What gives?

Upvotes: 0

Views: 1583

Answers (1)

Steven V
Steven V

Reputation: 16595

I think you need a few more explicit routes, since the router doesn't know the difference between the "catch all" of Admin/{controller}/{action}/{id} and {controller}/{action}/{id}. The first matched pattern is the one it uses.

You either need to get rid of the Admin/{controller}/{action}/{id} and anything under the admin prefix needs to be explicitly assigned as a route, or the opposite, remove the {controller}/{action}/{id} route, and explicitly create routes that should be apart of the root directory.

Upvotes: 1

Related Questions