Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 734
Rob Bird Avatar asked Sep 12 '15 06:09

Rob Bird


1 Answers

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!

like image 106
Rob Bird Avatar answered Sep 21 '22 07:09

Rob Bird