How to access RouteData from an ASP.Net 5 Tag Helper in MVC 6
Asked Answered
M

1

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?

Mantooth answered 12/9, 2015 at 6:7 Comment(0)
M
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!

Mantooth answered 13/9, 2015 at 11:34 Comment(4)
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.Annunciata
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.Mantooth
@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 #32533234 but it's been put on hold unfortunately (for inciting a religious war or something about opinions)Mantooth
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.Annunciata

© 2022 - 2024 — McMap. All rights reserved.