0

I'm curious whether this is possible, or as I suspect, by design not. In an ASP.NET MVC project I have multiple routes like this:

new Route(
                    url, // This can be arbitrary
                    new RouteValueDictionary {
                                                            {"area", "MyArea"},
                                                            {"controller", "MyController"},
                                                            {"action", "Index"}
                                                        },
                    new RouteValueDictionary(),
                    new RouteValueDictionary {
                                                            {"area", "MyArea"},
                                                        },
                    new MvcRouteHandler()))

I'd like to generate urls (or links) in the (Razor) views used by the actions of MyController. These urls should point to another action of MyController.

Now the problem is, there are multiple routes like above registered under different urls, so simply calling Html.ActionLink() or Url.Action() with the current route values yields a link that points to the url that's route first matches it. That's not necessarily the url the action is currently invoked from.

So basically what I'd like is take the current route and substitute the action with another one. I couldn't find any way to do that. The urls can be arbitrary, but if necessary, constraints can be applied, e.g. so that the url must contain an action token. Actually all of them currently do, so urls have the following structure:

/AnotherArea/SubSegment/{action} // Routes point from other areas to MyArea/MyController

These urls are there in Html.ViewContext.RouteData.Route.Url of the view, so that action token should be changed somehow when generating a new url. (Well, one could do that with string replacement, but I guess if there is a solution, it should be better than that.) Thank you for your time!

1
  • I'm used to one line break for a paragraph, sorry. Added three new ones :-).
    – Piedone
    Feb 6, 2012 at 22:05

1 Answer 1

0

Now I found a solution, pretty simple:

@Url.RouteUrl("RouteName", new { Action = "OtherAction" })

However this implies the knowledge of the currently used route's name. Since this isn't stored in the Route object itself I opted with the kind of hackish solution of storing the name in the route's DataTokens dictionary. That seemingly doesn't harm and since routes are filled through a service this convention of using DataTokens doesn't need to be kept in mind.

I'm wondering if there's a better solution, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.