Search code examples
c#asp.net-mvc-2html.actionlink

Html.ActionLink yields different results depending on the URL


I've got the URL http://localhost:xyz/HelloWorld, which directs to the HelloWorld action in the Home controller.

On the page that renders at the URL, I have an Html.ActionLink that points to the same page (yes, a link to the page you are currently on).

The issue is that this link only points to the page if the page is loaded as http://localhost:xyz/HelloWorld/ (with trailing slash). If the page is loaded as http://localhost:xyz/HelloWorld (no slash), it directs to the Index action of the Home controller.

I've tried several overloads, but I can't figure out what is causing this or how to fix it.

Html.ActionLink("Hello World", "HelloWorld", "Home");
Html.ActionLink("Hello World", "HelloWorld", "Home", null, null);
Html.ActionLink("Hello World", "HelloWorld", "Home", new { arg = 0 }, null);

These all have exactly the same result. They work fine if there is a trailing slash, and direct to http://localhost:xyz/ if there is not.

Can anyone explain this behavior or how to fix it?

EDIT (possibly relevant?):
When arg is present and not 0, the same page is shown at http://localhost:xyz/HelloWorld/arg, and has the "Hello World" link (which works perfectly fine), and a similar link that works flawlessly.

Html.ActionLink("Argument", "HelloWorld", "Home", new {arg = arg}, null);

This points to itself correctly, regardless of whether or not a trailing slash is present.

ROUTES:

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

routes.MapRoute(
  "Hello World",
  "HelloWorld/{arg}",
  new {controller = "Home", action = "HelloWorld", arg = ""}
);

Solution

  • Problem solved. I separated the routes for with and without an argument.

    routes.MapRoute(
     "Hello World",
     "HelloWorld",
     new {controller = "Home", action = "HelloWorld"}
    );
    
    routes.MapRoute(
     "Hello World With Arg",
     "HelloWorld/{arg}",
     new {controller = "Home", action = "HelloWorld", arg = ""}
    );