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

前端 未结 5 1404
半阙折子戏
半阙折子戏 2020-12-02 09:56

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.

W

相关标签:
5条回答
  • 2020-12-02 10:11

    Found it...

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

    ViewContext.ParentActionViewContext.RouteData.Values["action"]
    
    0 讨论(0)
  • 2020-12-02 10:11

    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 讨论(0)
  • 2020-12-02 10:15

    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"] 
    
    0 讨论(0)
  • 2020-12-02 10:25

    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;
    }
    
    0 讨论(0)
  • 2020-12-02 10:32

    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.

    0 讨论(0)
提交回复
热议问题