Search code examples
c#asp.net-mvcrazorasp.net-mvc-5

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

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

    OR

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