MVC 4 Getting the current scope, controller, and action

In my Layout.cshtml, I call RenderAction to show a menu for each page request:

 Html.RenderAction("NiceMenu", "Widgets", new {area = ""});

WidgetController needs to know that the parent instance of the Controller and Action calls it so that it can display the menu with the desired item selected.

How to know this in the action of the Nikmenen Controller ?

+4
source share
2 answers

You can use the ParentActionViewContext property of the ViewContext in the view of the child action:

var parentRouteValues = ViewContext.ParentActionViewContext.RouteData.Values;
@Html.RenderAction("NiceMenu", "Widgets",
             new
             {
                 area = parentRouteValues["area"],
                 controller = parentRouteValues["controller"],
                 action = parentRouteValues["action"]
             })
+4

var action = (ViewContext.RouteData.Values["action"] ?? "").ToString().ToLower();
var controller = (ViewContext.RouteData.Values["controller"] ?? "").ToString().ToLower();
var area = (ViewContext.RouteData.DataTokens["area"] ?? "").ToString().ToLower();
+7

All Articles