jdh
jdh

Reputation: 1

ASP.NET MVC AnchorLink not using route values?

I'm using AnchorLink on a very simple site with just two routes defined, one standard route and another area route for admin/{controller}/{action}/{id}. I'm at a URL like:

/admin/release/push/255

In that view I'm using:

@Html.AnchorLink("Confirm", "Confirm")

AnchorLink is rendering a link without the current request {id} included, ie. /admin/release/confirm! If I inspect the RouteValues I can see {id} is in there. If I explicity pass in the route values from teh current request, as in:

@Html.AnchorLink("Confirm this release", "Confirm", Url.RequestContext.RouteData.Values)

Then it works, I get the URL /admin/release/confirm/255. Why does the explicit version where I pass in the current request route values work, but the implicit one, without the route values argument, which I thought would pick up the current request route values, doesn't? I know the above is a solution, but it's ugly and there's some underlying reason why the AnchorLink without the route values isn't working as I expect?!

Upvotes: 0

Views: 256

Answers (1)

Phil Bennett
Phil Bennett

Reputation: 4839

MVC is doing exactly the right thing here. It's not to know you require the Id parameter for your anchor link or not -- in other words its not trying anything clever to pre-parse and examine the link. It will only do that when its being rendered. And in your case without the id parameter specified somewhere its going to use the default route.

If you find yourself writing that same code all over the place you could easily extract it out into a static helper class. That can get rid of the ugliness.

Upvotes: 0

Related Questions