html - 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 帮助程序类代码,发现它设置了从布局传递的正确操作和控制器。
不知道这个网址在哪里被更改。
请建议。
解决方案
使用以下代码:
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" })
推荐阅读
- r - 克隆到 R 时出现 AzureDevOps 身份验证问题
- javascript - window.open 函数只在 foreach 循环中运行一次
- java - 检查多个文件中的重复行(数据)
- angular - 如何将第三方开发者开发的模块集成到主要的 Angular 应用程序中
- go - sendgrid 去发送获取错误意外 EOF
- r - 将列表列表转换为矩阵
- angular - 在 angular 的 formBuilder.group 反应形式中添加动态属性
- amazon-web-services - AWS Step Functions 架构
- popup - 处理弹出窗口?我们现在得到白页
- linkedin - LinkedIn Share Button 帖子表单不正确