How Can I Determine The Current Controller or Action in an Html Helper
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.
public static MvcHtmlString LoginLink(this HtmlHelper helper)
{
string currentControllerName =
(string)helper.ViewContext.RouteData.Values["controller"];
string currentActionName =
(string)helper.ViewContext.RouteData.Values["action"];
bool isAuthenticated =
helper.ViewContext.HttpContext.Request.IsAuthenticated;
// more stuff here
}
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!
You can follow me on twitter here or subscribe to my blog here.