Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 Getting the current Area, Controller and Action

In my Layout.cshtml I call RenderAction to show the menu for every page request:

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

The WidgetController needs to know the parent executing Controller and Action calling it so that it can render the menu with the right item highlighted.

How can the Widget Controller's NiceMenu action know this?

like image 328
Ian Vink Avatar asked Dec 07 '22 04:12

Ian Vink


2 Answers

this is how we do it

var action = (ViewContext.RouteData.Values["action"] ?? "").ToString().ToLower();
var controller = (ViewContext.RouteData.Values["controller"] ?? "").ToString().ToLower();
var area = (ViewContext.RouteData.DataTokens["area"] ?? "").ToString().ToLower();
like image 89
Matt Bodily Avatar answered Dec 10 '22 11:12

Matt Bodily


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

var parentRouteValues = ViewContext.ParentActionViewContext.RouteData.Values;
@Html.RenderAction("NiceMenu", "Widgets",
             new
             {
                 area = parentRouteValues["area"],
                 controller = parentRouteValues["controller"],
                 action = parentRouteValues["action"]
             })
like image 26
Ufuk Hacıoğulları Avatar answered Dec 10 '22 12:12

Ufuk Hacıoğulları