【问题标题】:How to retrieve controller and action names from Html.Action that is rendered from different controller and action in ASP.NET MVC如何从 ASP.NET MVC 中的不同控制器和动作呈现的 Html.Action 中检索控制器和动作名称
【发布时间】:2015-12-12 16:25:35
【问题描述】:

我在 ASP.NET MVC 中检索控制器和操作名称时遇到问题。下面是我的场景。

第 1 步:

我正在布局页面中呈现 Html.Action("sidebar","Helper")。所以它的 Controller 和 Action 应该是这样的。

第 2 步:

我正在尝试将当前控制器名称和操作名称传递给侧边栏视图的视图。例如,如果我在 HomeController,控制器名称将是“Home”而不是“Helper”,因为 HelperController 在布局页面中,并且包含在每个页面中。我正在尝试检索第 3 步中的名称。

第 3 步

public class HelperController:Controller{
    public PartialViewResult sidebar()
    {
       string con_action = ControllerContext.RouteData.Values["controller"].ToString()+"-"+ControllerContext.RouteData.Vaues["action"].ToString();
    }
}

我的问题:即使我导航到 HomeController 的索引操作,它也会继续返回控制器名称“Helper”和操作名称“侧边栏”。我该如何解决这个问题?

【问题讨论】:

标签: c# asp.net asp.net-mvc


【解决方案1】:

您可以像这样在布局页面中将当前控制器名称和动作名称作为参数传递

@Html.Action("sidebar", "Helper", new { thisController = ViewContext.RouteData.Values["controller"].ToString(), thisAction = ViewContext.RouteData.Values["action"].ToString() })

然后在 Helper 控制器中访问它们

    public class HelperController:Controller{
            public PartialViewResult sidebar(string thisController, string thisAction)
            {
               string con_action = thisController + "-" + thisAction;
               ...
            }
        }

【讨论】:

  • 非常感谢。这正是我想要的。对我很有帮助。
猜你喜欢
  • 1970-01-01
  • 2013-08-17
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 2011-03-19
相关资源
最近更新 更多