How to get parent view from partial view

2019-01-18 10:33发布

问题:

I have a partial view as part of the _Layout.cshtml, so that it gets rendered on multiple pages. Think of the partial view as a menu that gets displayed on every page on the website.

When one of these links in the menu of the partial view is clicked, I can only access/see in the Action Method that gets called the partial view, like it's name etc.

But what I really need to have is the View that the partial view was on when the item was clicked.

How can I get this?

回答1:

You can use ParentActionContext

For example

 var controller = ControllerContext.ParentActionViewContext.RouteData.Values["Controller"] as string;
 var action = ControllerContext.ParentActionViewContext.RouteData.Values["Action"] as string;

Update

From the view this call should do what you need

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()
@HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString()