How to make routelink return the correct URL?

16.7k Views Asked by At

here is the procedure to duplicate the issue.

  1. start new mvc 4 project.
  2. add the following lines to the RegisterRoutes() method just before the "Default" route

    routes.MapRoute(
            name: "Test",
            url: "Test/{action}",
            defaults: new { controller = "Test", action = "Index" }
    );
    
  3. add the following to Index.cshtml and About.cshtml

    @Html.RouteLink("link to TestController", "Test")
    

As you can see that the generated html code is different for the 2 pages. I would expect the URL is "/Test" which is rendered correctly for Index.cshtml, but it become "/Test/About" for About.cshtml.

My question is if there is any documented way to generate the same correct URL. The above example is created just for demonstration purpose. I would like to use the routing table information to generate menu.

4

There are 4 best solutions below

0
On

Quickest way would be to just specify a blank action.

@Html.RouteLink("link to TestController", "", "Test")

This will produce /Test

0
On

For those who arrive here looking for .netcore razor page RouteLink syntax, don't use RouteLink's "page" reserved member. It will not work for the routeValues object as some have suggested. Instead, use the following format:

<a asp-page="RazorPage">RazorPage</a>

This handles trailing and the absence of trailing forward slashes. The RazorPage is the name of the page without any characters after the first ".".

0
On

Register your route

 routes.MapRoute(
                name: "TestUrl",
                url: "Test",
                defaults: new { controller = "TestController", action = "TestAction" }
            );

add the following to TestAction.cshtml

 @Html.RouteLink("Test", "TestUrl")

Now your URL is /Test, hoping this will help you.

1
On

It seems the engine is setting the action route value from the current page ("Index", "About"). So one way to fix this is to "unset" that route value:

@Html.RouteLink("link to Test Controller", "Test", new { action = String.Empty })