【问题标题】:ASP.NET MVC4 menu link activate when controller and action matches控制器和操作匹配时激活 ASP.NET MVC4 菜单链接
【发布时间】:2013-07-04 02:47:18
【问题描述】:

我有一个 ASP.NET MVC4 应用程序,我的左侧导航菜单位于 CommonController 下,所以从我的 _Layout.cshtml 中我将其呈现为:

<div class="leftmenu">        
    @Html.Action("LeftMenu", "Common")
</div><!--leftmenu-->

现在,在我的局部视图中 LeftMenu 我拥有用于​​显示菜单项的所有 HTML 代码,我想做的是根据当前页面控制器和操作突出显示正确的菜单项。

LeftMenu.cshtml

<ul class="nav nav-tabs nav-stacked">
<li class="nav-header">Navigation Menu</li>
<li>@Html.MenuLink("Test Link", "Index", "Home", "active",true)</li>
......

现在我正在使用以下帮助代码:

public static HtmlString MenuLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string activeClass, bool checkAction)
        {
            string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");

            if (string.Compare(controllerName, currentController, StringComparison.OrdinalIgnoreCase) == 0 && ((!checkAction) || string.Compare(actionName, currentAction, StringComparison.OrdinalIgnoreCase) == 0))
            {
                return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = activeClass });
            }

            return htmlHelper.ActionLink(linkText, actionName, controllerName);

        }

我遇到的问题是 currentController 是“Common”,因为它位于 LeftMenu 部分视图的位置。

我需要获取主页当前控制器和当前操作以使其工作。

关于如何解决它的任何线索或建议?

非常感谢

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 menu


    【解决方案1】:

    我建议将“leftMenu.cshtml”移动到 _Layout.cshtml 旁边的共享视图文件夹中,并在菜单中使用它,如下所示:

    <div class="leftmenu">        
       @Html.Partial("LeftMenu")
    </div>
    <!--leftmenu-->
    

    这样您将在自定义 Helper 中获得正确的操作名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多