Getting controller name from razor

An addendum to Koti Panga's answer: the two examples he provided are not equivalent.

This will return the name of the controller handling the view where this code is executed:

var handlingController = this.ViewContext.RouteData.Values["controller"].ToString();

And this will return the name of the controller requested in the URL:

var requestedController = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

While these will certainly be the same in most cases, there are some cases where you might be inside a partial view belonging to a different controller and want to get the name of the controller "higher-up" in the chain, in which case the second method is required.

For example, imagine you have a partial view responsible for rendering the website's menu links. So for every page in your website, the links are prepared and passed to the view from an action called SiteMenuPartial in LayoutController.

So when you load up /Home/Index, the layout page is retrieved, the SiteMenuPartial method is called by the layout page, and the SiteMenuPartial.cshtml partial view is returned. If, in that partial view, you were to execute the following two lines of code, they would return the values shown:

/* Executes at the top of SiteMenuPartial.cshtml */
@{
    // returns "Layout"
    string handlingController = this.ViewContext.RouteData.Values["controller"].ToString();

    // returns "Home"
    string requestedController = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
}

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

MVC 3

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

MVC 4.5 Or MVC 5

@ViewContext.RouteData.Values["controller"].ToString();

@{ 
    var controllerName = this.ViewContext.RouteData.Values["controller"].ToString();
}

OR

@{ 
    var controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
}