Using Attribute Routing you can define a route name. Is there a way I can get the name of the used route from inside my view?
-
1Here is a similar question about how to get this info in the controller. The answer could be used to also get it in the view: http://stackoverflow.com/questions/363211/how-can-i-get-the-route-name-in-controller-in-asp-net-mvc – Richard Garside Apr 20 '17 at 12:54
3 Answers
According to this answer, you can use:
@{ var x = ViewContext.RouteData.Values["Action"]; }
to get route data. Then according to the right answer of this post: "How to get a custom attribute from object instance in C#", you can pull out the attributes.
-
The first part I already knew about, the 2nd part... I'm not sure how that helps. – mpen Dec 31 '12 at 01:51
This doesn't sound like a real good idea. You should probably add the route name to view data or the view model instead.

- 15,275
- 27
- 77
- 131
-
Then I would have to do it in every single action. I want to use it in my layout. – mpen Dec 30 '12 at 05:32
MapMvcAttributeRoutes
has multiple overloads which expects a parameter for IDirectRouteProvider
implementation. This interface is responsible for generating routes. The default implementation for this interface is DefaultDirectRouteProvider
. Create a custom class that inherits from DefaultDirectRouteProvider
and override required methods like GetActionDirectRoutes
or GetControllerDirectRoutes
. In this method you will get RouteEntry
which contains the route name. You can add this name to datatokens.