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

asp.net Mvcasp.net Mvc-Routing

asp.net Mvc Problem Overview


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.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

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"] 

Solution 2 - asp.net Mvc

Found it...

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

ViewContext.ParentActionViewContext.RouteData.Values["action"]

Solution 3 - asp.net Mvc

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;
}

Solution 4 - asp.net Mvc

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.

Solution 5 - asp.net Mvc

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);
}    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJBecktonView Question on Stackoverflow
Solution 1 - asp.net MvcRupert BatesView Answer on Stackoverflow
Solution 2 - asp.net MvcJBecktonView Answer on Stackoverflow
Solution 3 - asp.net MvcCarlos Martinez TView Answer on Stackoverflow
Solution 4 - asp.net MvcjahuView Answer on Stackoverflow
Solution 5 - asp.net MvcLucent FoxView Answer on Stackoverflow