首页 > 解决方案 > html助手。ActionLink 总是设置当前控制器而不是传递另一个控制器

问题描述

我正在使用 HtmlHelper 类,其中我使用了一些代码,并将其设置为我的布局导航栏作为菜单。

下面是相同的代码:

 public static MvcHtmlString MenuLink(this HtmlHelper helper,string text, string action, string controller)
        {
            var routeData = helper.ViewContext.RouteData.Values;
            var currentController = routeData["controller"];
            var currentAction = routeData["action"];

            if (String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase))
            {
                return new MvcHtmlString("<li class=\"nav-item active\">" + helper.ActionLink(text, action, controller, new { @class="nav-link" }) + "</li>");
            }
            return new MvcHtmlString("<li class=\"nav-item\">" + helper.ActionLink(text, action, controller, new { @class = "nav-link" }) + "</li>");
        }

我在布局页面中设置了如下菜单:

 @Html.MenuLink("Search", "Search", "Home")

现在,当我运行应用程序时,它首先加载登录页面,其中登录路径为:Account/Login

现在在搜索菜单中,当我悬停此菜单时,我发现此菜单 url 也设置为 Account/Search?Length=4。

但是我为这个菜单传递了“主页”控制器。

我调试了 html 帮助程序类代码,发现它设置了从布局传递的正确操作和控制器。

不知道这个网址在哪里被更改。

请建议。

标签: htmlbootstrap-4asp.net-mvc-5

解决方案


使用以下代码:

 public static MvcHtmlString MenuLink(this HtmlHelper helper,string text, string action, string controller)
        {
            var routeData = helper.ViewContext.RouteData.Values;
            var currentController = routeData["controller"];
            var currentAction = routeData["action"];

            if (String.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase))
            {
                return new MvcHtmlString("<li class=\"nav-item active\">" + helper.ActionLink(text, action, controller,null, new { @class="nav-link" }) + "</li>");
            }
            return new MvcHtmlString("<li class=\"nav-item\">" + helper.ActionLink(text, action, controller,null, new { @class = "nav-link" }) + "</li>");
        }

当你使用

helper.ActionLink(text, action, controller,new { @class="nav-link" })

然后它指的是当前控制器,因为您没有指定 routeValue 所以,当您想从一个控制器重定向到另一个控制器时,如果没有 routevalue 到重定向方法,则将 routevalue 指定为 null。

所以,使用helper.ActionLink(text, action, controller,null, new { @class="nav-link" })


推荐阅读