views:

269

answers:

1

Hi there.

I have a question regarding RouteLink vs. ActionLink.

Consider the following route

routes.MapRoute("Routename1",
    "{someEnum}/SpecificAction/{id}/{stringId}",
    new { controller = "MyController", id = (int?)null, stringId= (string)null, action = "SpecificAction" },
    new { someEnum= "(EnumVal1|EnumVal2)" }
);

The weird {someEnum} part is because I use a general controller for all values of an enum that form the typical controller part of a url. For instance, /EnumVal1/Action/ and /EnumVal2/Action/ use the same controller. That's not part of the problem, however.

Consider the following two ways of linking:

<%=Html.RouteLink("Click me","Routename1", new { id = 32, stringId = "Yatzy" })%> 
<%=Html.ActionLink("Click me", "SpecificAction", "EnumVal1", new { id = 32, stringId = "Yatsy" }, null)%>

The RouteLink generates the correct url, which would be /EnumVal1/SpecificAction/32/Yatzy

The ActionLink generates an url that looks like /EnumVal1/SpecificAction/32?stringId=Yatzy

Why is this? Could someone explain this to me, please.

+1  A: 

RouteLink can only ever use the one route you specify. ActionLink will use the first matching route, whether it's the one you intended or not. Your two examples are probably matching different routes.

Phil Haack's routing debugger would help clarify this.

Craig Stuntz
Hi. This was my initial thought as well, but when I entered the given URL into the debugtool, for instance: /EnumVal1/SpecificAction/32/Yatzy, - it matches the same route that I use for RouteLink (It's also the only route that matches).
Terje
You're confusing URL parsing with link generation. They're two different sides of the routing coin. That URL parsing works does not mean that `ActionLink` generation will also match the route you expect.
Craig Stuntz
Oh. How would I use the routing debugger to see the right side of the coin? :)
Terje
I'm not sure I understand the problem here: `RouteLink` does exactly what you want, and it's faster than `ActionLink`. Why not just use it?
Craig Stuntz
I am using RouteLink, - the question I posed was an attempt to find out why one of them generated a friendly URL, while the other didn't.
Terje