Getting controller name from razor

Icemanind picture Icemanind · Oct 17, 2014 · Viewed 48.5k times · Source

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.

Answer

Koti Panga picture Koti Panga · Oct 17, 2014
@{ 
    var controllerName = this.ViewContext.RouteData.Values["controller"].ToString();
}

OR

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