How to get the current controller and actions from inside the Child action?

I have a part of my view that is rendered through a RenderAction that invokes a child action. How can I get the parent controller and action from this child action.

When i use ..

@ViewContext.RouteData.Values["action"] 

I am returning the name of the child action, but I need the Parent / Call action.

thank

BTW I am using MVC 3 with Razor.

+51
asp.net-mvc asp.net-mvc-routing
Dec 10 2018-10-10
source share
5 answers

And if you want to access this from the child action itself (and not from the view), you can use

 ControllerContext.ParentActionViewContext.RouteData.Values["action"] 
+70
Dec 17 '10 at 9:44
source share

Found...

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

 ViewContext.ParentActionViewContext.RouteData.Values["action"] 
+20
Dec 10 '10 at 19:08
source share

If the partial part is inside another partial, this will not work unless we find the top most of the parent representations. You can find this with this:

 var parentActionViewContext = ViewContext.ParentActionViewContext; while (parentActionViewContext.ParentActionViewContext != null) { parentActionViewContext = parentActionViewContext.ParentActionViewContext; } 
+15
Oct. 23
source share

I had the same problem and came to the same solution as Carlos Martinez, but 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 helps others who have the same problem.

+1
May 13 '14 at 11:20
source share

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); } 
0
Aug 15 '12 at 19:29
source share



All Articles