Steve Smith's Blog

Musings on Software and the Developer Community

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.

    kick it on DotNetKicks.com

Friday, 02 July 2010

Comments

 avatar

jrnail23 said on 06 Jul 2010 at 11:20 AM

Hey Steve, thanks for the tip!

If you arrive at the view via the app's default url, does the route data actually contain the controller and action names, or does it just contain empty strings for those values? (This seems to happen in various places where views, etc are chosen by convention, and it kinda mucks up some of my testing here & there)


 avatar

Anonymous said on 08 Jul 2010 at 1:41 PM

Route data will always have the "Controller' and "Action" names because to get to a page, the request has to go through MVC pipeline


Leave a Comment

Please join the discussion and share your thoughts.