57

I have a portion of my view that is rendered via RenderAction calling a child action. How can I get the Parent controller and Action from inside this Child Action.

When I use..

@ViewContext.RouteData.Values["action"]

I get back the name of the Child Action but what I need is the Parent/Calling action.

Thanks

BTW I am using MVC 3 with Razor.

JBeckton
  • 7,095
  • 13
  • 51
  • 71

5 Answers5

74

And if you want to access this from within the child action itself (rather than the view) you can use

ControllerContext.ParentActionViewContext.RouteData.Values["action"] 
Rupert Bates
  • 3,041
  • 27
  • 20
  • 1
    For anyone confused between this answer and JBeckton's answer, the difference is in whether you're getting this value from inside your Controller or inside your View. Use ControllerContext or ViewContext to match as appropriate. The original question appears to be using it from within a View given the starting @ sign for the code. – TheAtomicOption Jan 07 '20 at 17:19
22

Found it...

how-do-i-get-the-routedata-associated-with-the-parent-action-in-a-partial-view

ViewContext.ParentActionViewContext.RouteData.Values["action"]
Community
  • 1
  • 1
JBeckton
  • 7,095
  • 13
  • 51
  • 71
17

If the partial is inside another partial, this won't work unless we find the top most parent view content. You can find it with this:

var parentActionViewContext = ViewContext.ParentActionViewContext;
while (parentActionViewContext.ParentActionViewContext != null)
{
    parentActionViewContext = parentActionViewContext.ParentActionViewContext;
}
Carlos Martinez T
  • 6,458
  • 1
  • 34
  • 40
1

I had the same problem and came up with same solution as Carlos Martinez, except I turned it into an extension:

public static class ViewContextExtension
{
    public static ViewContext TopmostParent(this ViewContext context)
    {
        ViewContext result = context;
        while (result.ParentActionViewContext != null)
        {
            result = result.ParentActionViewContext;
        }
        return result;
    }
}

I hope this will help others who have the same problem.

jahu
  • 5,427
  • 3
  • 37
  • 64
0

Use model binding to get the action name, controller name, or any other url values:

routes.MapRoute("City", "{citySlug}", new { controller = "home", action = "city" });

[ChildActionOnly]
public PartialViewResult Navigation(string citySlug)
{
    var model = new NavigationModel()
    {
        IsAuthenticated = _userService.IsAuthenticated(),
        Cities = _cityService.GetCities(),
        GigsWeBrought = _gigService.GetGigsWeBrought(citySlug),
        GigsWeWant = _gigService.GetGigsWeWant(citySlug)
    };

    return PartialView(model);
}    
Lucent Fox
  • 1,737
  • 1
  • 16
  • 24