Getting controller name from razor

I seem to be having a difficult getting something that should be easy. From within my view, using Razor, I'd like to get the name of the current controller. For example, if I'm here:

http://www.example.com/MyController/Index

How can I get the controller name, MyController from a Razor expression:

@* Obviously this next line doesn't work
    @Controller.Name
*@

I'm new to MVC, so if this is an obvious answer, don't attack me to bad.


Solution 1:

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

OR

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

Solution 2:

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();
}

Solution 3:

@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();