7

I am trying to get hold of the current route so that I can highlight the active page in a set of links using a Tag Helper.

The TagHelperContext doesn't give me access to anything useful. How can I get a reference to the RouteData?

Rob Bird
  • 3,764
  • 2
  • 28
  • 38

1 Answers1

16

I eventually found the answer described here: https://github.com/aspnet/Announcements/issues/28

You can import the ViewContext using property injection by using a new attribute. You need to create a property in you tag helper class like this:

[ViewContext]
public ViewContext ViewContext { get; set; }

You can then access the current controller or action like so:

var pageController = ViewContext.RouteData.Values["controller"];
var pageAction = ViewContext.RouteData.Values["action"];

Maybe I posted this question before doing enough research, but this was not entirely obvious, so I hope this helps someone else!

Rob Bird
  • 3,764
  • 2
  • 28
  • 38
  • the way I've been doing it is to pass in those things as attributes to my taghelper the same way Microsoft does it for AnchorTagHelper ie asp-controller and asp-action so that the consumer of my taghelper can specify it rather than assuming to use the same as the current request. – Joe Audette Sep 14 '15 at 14:56
  • Thanks Joe - just to clarify, I am doing this too. I am comparing what is in the route data to the asp-controller and asp-action to see if the link in question is currently active. i.e highlight in the menu. So if this is a shared razor view you cannot pass in the currently active one, it has to be dynamic. Hope that makes sense. – Rob Bird Sep 14 '15 at 22:56
  • @Joe - also, out of interest are you naming them asp-controller or just controller? I'm not sure if I should be using the asp- prefix or not. I raised http://stackoverflow.com/questions/32532734/should-my-custom-asp-net-5-mvc-6-tag-helpers-have-an-asp-prefix but it's been put on hold unfortunately (for inciting a religious war or something about opinions) – Rob Bird Sep 14 '15 at 23:01
  • 2
    I used asp-controller and asp-action to be consistent with the same attributes on anchortaghelper but for all my other attributes I'm using a custom prefix. – Joe Audette Sep 14 '15 at 23:50