If you’re writing an HTML Helper for ASP.NET MVC you may want to do something different based on whether the page that is to be rendered was arrived at via a particular controller or controller action. I found the following code which does just this in one of the ASP.NET MVC Themes available from the www.asp.net web site (the Dark theme, I believe it’s called).
Note that I’ve already modified this code to work with the new ASP.NET 4 string encoding and the MvcHtmlString type, as I wrote about previously.
As you can see, the HtmlHelper has a ViewContext property, which allows you to access RouteData and ultimately from there determine the controller and/or action that was used for this request. Incidentally, you can also use the ViewContext to get to HttpContext and determine whether the request is authenticated as well.
And that’s it!