[英]How to retrieve controller and action names from Html.Action that is rendered from different controller and action in ASP.NET MVC
I am having a problem in retrieving Controller and Action names in ASP.NET MVC. 我在检索ASP.NET MVC中的控制器和动作名称时遇到问题。 Below is my scenario.
以下是我的情况。
Step 1: 第1步:
I am rendering a Html.Action("sidebar","Helper") in my layout page. 我正在布局页面中呈现Html.Action(“ sidebar”,“ Helper”)。 So Controller and Action for it would be like this.
因此,控制器和操作将像这样。
Step 2: 第2步:
I am trying to pass the current controller name and action name to the view of sidebar view. 我正在尝试将当前控制器名称和操作名称传递到侧边栏视图的视图。 For example, if I am at HomeController, controller name would be 'Home' and not 'Helper' because HelperController is in the layout page and that is included in every page.
例如,如果我在HomeController,控制器名称将为“ Home”而不是“ Helper”,因为HelperController在布局页面中并且包含在每个页面中。 I am trying to retrieve the names as in Step 3.
我正在尝试按照步骤3检索名称。
Step 3 第三步
public class HelperController:Controller{
public PartialViewResult sidebar()
{
string con_action = ControllerContext.RouteData.Values["controller"].ToString()+"-"+ControllerContext.RouteData.Vaues["action"].ToString();
}
}
My problem: It keep returning the controller name "Helper" and action name "sidebar" even if I navigate to Index action of HomeController. 我的问题:即使导航到HomeController的Index操作,它仍会返回控制器名称“ Helper”和操作名称“ sidebar”。 How can I fix that problem?
我该如何解决这个问题?
You can pass the current controller name and action name as parameters in the layout page like this 您可以像这样在布局页面中将当前控制器名称和操作名称作为参数传递
@Html.Action("sidebar", "Helper", new { thisController = ViewContext.RouteData.Values["controller"].ToString(), thisAction = ViewContext.RouteData.Values["action"].ToString() })
and then access them in the Helper controller 然后在Helper控制器中访问它们
public class HelperController:Controller{
public PartialViewResult sidebar(string thisController, string thisAction)
{
string con_action = thisController + "-" + thisAction;
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.