MVC ActionLink omits action when action equals default route value
Asked Answered
E

1

9

I have the following routes defined for my application:

routes.MapRoute(
    "Referral", // Route name
    "{referralCode}", // URL with parameters
    new { controller = "Home", action = "Index" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}", // URL with parameters
    new { controller = "Home", action = "Index" } // Parameter defaults
);

And I'm trying to create an ActionLink to go on the Index action on my AdminController:

@Html.ActionLink("admin", "Index", "Admin")

However, when the view is executed the ActionLink renders as (Index action value is omitted):

<a href="/Admin">admin</a>

Normally this would be ok, but it's causing a collision with the "Referral" route.

NOTE: If I instead use ActionLink to render a different action like "Default," the ActionLink renders correctly:

<a href="/Admin/Default">admin</a>

The fact that the "Default" action renders correctly leads me to believe the problem has to do with the default value specified for the route. Is there anyway to force ActionLink to render the "Index" action as well?

Exorcism answered 31/12, 2010 at 17:42 Comment(0)
W
9

Remove the default action parameter on your Default route:

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

That will force the action to always be specified in the url.

Wellread answered 31/12, 2010 at 17:49 Comment(1)
Thanks for that. I ended up removing both the action and controller from the route defaults of the "Default" route and specified referralCode = UrlParameter.Optional for the "Referral" route.Exorcism

© 2022 - 2024 — McMap. All rights reserved.