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.
4 Comments
Daily tech links for .net and related technologies - June 5-7, 2010 said
Daily tech links for .net and related technologies - June 5-7, 2010 Web Development Introducing “Razor
jrnail23 said
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)
Anonymous said
Route data will always have the "Controller' and "Action" names because to get to a page, the request has to go through MVC pipeline
Sidebuck said
It is actually the first time that I get the chance to read a blog post on this cool website, and I found some interesting information here, so thank you.