当控制器和动作匹配时,ASP.NET MVC4菜单链接激活

时间:2013-07-02 17:04:30

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

我有一个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局部视图所在的位置。

我需要获取主页当前控制器和当前操作才能使其正常工作。

有关如何解决问题的任何线索或建议?

非常感谢

1 个答案:

答案 0 :(得分:0)

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

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

这样您就可以在自定义助手中获得正确的操作名称。