4

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?

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 1
    Here 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 Answers3

2

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.

Community
  • 1
  • 1
Tohid
  • 6,175
  • 7
  • 51
  • 80
1

This doesn't sound like a real good idea. You should probably add the route name to view data or the view model instead.

devlife
  • 15,275
  • 27
  • 77
  • 131
1

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.

Mike M
  • 4,358
  • 1
  • 28
  • 48
Raj
  • 19
  • 2