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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With