asp.net-mvc 如何从子动作内部获取当前控制器和动作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4412310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current controller and action from inside Child action?
提问by JBeckton
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.
我有一部分视图是通过 RenderAction 调用子操作呈现的。如何从这个子操作中获取父控制器和操作。
When I use..
当我使用..
@ViewContext.RouteData.Values["action"]
I get back the name of the Child Action but what I need is the Parent/Calling action.
我取回了子操作的名称,但我需要的是父/调用操作。
Thanks
谢谢
BTW I am using MVC 3 with Razor.
顺便说一句,我正在将 MVC 3 与 Razor 一起使用。
回答by Rupert Bates
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"]
回答by JBeckton
Found it...
找到了...
how-do-i-get-the-routedata-associated-with-the-parent-action-in-a-partial-view
how-do-i-get-the-routedata-related-with-the-parent-action-in-a-partial-view
ViewContext.ParentActionViewContext.RouteData.Values["action"]
回答by Carlos Martinez T
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;
}
回答by jahu
I had the same problem and came up with same solution as Carlos Martinez, except I turned it into an extension:
我遇到了同样的问题,并提出了与 Carlos Martinez 相同的解决方案,但我将其变成了扩展:
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.
我希望这会帮助其他有同样问题的人。
回答by Lucent Fox
Use model binding to get the action name, controller name, or any other url values:
使用模型绑定来获取操作名称、控制器名称或任何其他 url 值:
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);
}