6

Is there a way to use HttpContext or the View context to get the current action name?

I can get the controller name using

    var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;

    if (routeValues != null) 
    {
        if (routeValues.ContainsKey("controller"))
        {
            controllerName = HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();
        }
    }
}
Charles
  • 50,943
  • 13
  • 104
  • 142
Chris Ballance
  • 33,810
  • 26
  • 104
  • 151
  • possible duplicate of [ASP.NET MVC4: Get controller and action name from within controller?](http://stackoverflow.com/questions/18248547/asp-net-mvc4-get-controller-and-action-name-from-within-controller) – Ilya Sulimanov Dec 17 '13 at 06:35

2 Answers2

17
var routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
if (routeValues != null) 
{
    if (routeValues.ContainsKey("action"))
    {
        var actionName = routeValues["action"].ToString();
    }
}
Peter B
  • 22,460
  • 5
  • 32
  • 69
Chris Ballance
  • 33,810
  • 26
  • 104
  • 151
0
ViewContext.RouteData.Values["action"]

As far as I know, ViewContext.RouteData.Values will never be null and will always have the keys "controller" and "action". Please correct me if I am wrong.

Bassem
  • 2,736
  • 31
  • 13