Matthew Verstraete
Matthew Verstraete

Reputation: 6781

Html.ActionLink generates the wrong URL, aslways adding Terminal/ to the URL

When I try to generate an HTML link using

@Html.ActionLink("Edit Carrier", "EditCarrier", "CustomerCare")

I would expect it to generate the URL /CustomerCare/EditCarrier/ but no matter what view I place it in the URL always gets generated as /Terminal/CustomerCare/EditCarrier/ and am I not sure why /Terminal/ is being added to the route. This is my first time NOT using Attribute Routing, and it is not an option to use it in this project. From looking around on the web I setup my RouteConfig.cs file as:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        routes.MapRoute(
            name: "Terminals",
            url: "Terminal/{controller}/{action}/{id}",
            defaults: new { id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

What am I missing here?

Upvotes: 1

Views: 668

Answers (1)

Kevin Brechbühl
Kevin Brechbühl

Reputation: 4727

This is because the route Terminals matches first when you request the url. If you don't use this route, then you can simply remove it from RouteConfig.cs, then the url will be /CustomerCare/EditCarrier/. If you need the Terminals route for any controller, you can add constraints to it:

routes.MapRoute(
   name: "Terminals",
   url: "Terminal/{controller}/{action}/{id}",
   defaults: new { id = UrlParameter.Optional },
   constraints: new { controller = @"ControllerWhoNeedsThisRoute" }
);

EDIT: Alternative you could also use @Html.RouteLink() and add the route name for generating the url. But then you need to specify the controller and the action in parameters. The second parameter is the name of the route to use:

@Html.RouteLink("Edit Carrier", "Default", new { controller = "CustomerCare", action = "EditCarrier" })

Upvotes: 3

Related Questions