Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What is child action method in MVC?

What is an MVC Child Action. A Child Action in ASP.NET MVC is kind of similar to that of a User Control in ASP.NET web forms. It allows for a controller to execute for a portion of the rendered area of a view, like in Web Forms where you can execute a UserControl for a portion of the rendered area of a page.

What is the default action for a controller?

By default, the Index() method is a default action method for any controller, as per configured default root, as shown below. routes. MapRoute( name: "Default", url: "{controller}/{action}/{id}/{name}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.


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

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.