Icemanind Icemanind - 4 months ago 18
C# Question

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.

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

OR

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