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

断了今生、忘了曾经 提交于 2019-11-27 11:05:48

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

Found it...

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

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

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

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.

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);
}    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!