asp.net mvc Html.ActionLink() 保留我不想要的路由值
-
13-09-2019 - |
题
我认为有以下 ActionLink
<%= Html.ActionLink("LinkText", "Action", "Controller"); %>
它会创建以下 URL http://mywebsite.com/Controller/Action
假设我在末尾添加一个 ID,如下所示: http://mywebsite.com/Controller/Action/53 并导航至该页面。在此页面上,我有上面指定的标记。现在,当我查看它创建的 URL 时,它看起来像这样:
http://mywebsite.com/Controller/Action/53 (注意添加ID)
但我希望它删除 ID 并看起来像原来一样,就像这样 http://mywebsite.com/Controller/Action (注意这里没有ID)
我有什么想法可以解决这个问题吗?我不想使用硬编码的 URL,因为我的控制器/操作可能会改变。
解决方案
的解决方案是用户自己指定路线值(低于第三个参数)
<%= Html.ActionLink("LinkText", "Action", "Controller",
new { id=string.Empty }, null) %>
其他提示
这听起来像你需要注册一个第二个“行动只有”路线,并使用Html.RouteLink()。首先这样注册在你的应用的路由启动:
routes.MapRoute("ActionOnly", "{controller}/{action}",
new { controller = "Home", action = "Index" } );
然后,而不是ActionLink的创建这些链路使用:
Html.RouteLink("About","ActionOnly")
问题是内置的方法都从您目前的以及所提供内容的网址输入。你可以试试这个:
<%= Html.ActionLink("LinkText", "Action", "Controller", new { id = ""}) %>
这应该手动擦拭id参数。
不知道为什么,但它并没有为我工作(因为MVC2 RC的可能)。创建urlhelper方法=>
public static string
WithoutRouteValues(this UrlHelper helper, ActionResult action,params string[] routeValues)
{
var rv = helper.RequestContext.RouteData.Values;
var ignoredValues = rv.Where(x=>routeValues.Any(z => z == x.Key)).ToList();
foreach (var ignoredValue in ignoredValues)
rv.Remove(ignoredValue.Key);
var res = helper.Action(action);
foreach (var ignoredValue in ignoredValues)
rv.Add(ignoredValue.Key, ignoredValue.Value);
return res;
}
我明确设置操作名称为“动作/”。似乎有点像一个黑客,但它是一个快速解决方案。
@Html.ActionLink("Link Name", "Action/", "Controller")
另一种方法是使用ActionLink的(的HtmlHelper,字符串,字符串,RouteValueDictionary)过载,则没有必要把空的最后一个参数
<%= Html.ActionLink("Details", "Details", "Product", new RouteValueDictionary(new { id=item.ID })) %>
Html.ActionLink 的重载在 MVC 的更高版本中发生了更改。在 MVC 5 及更高版本上。执行此操作的方法如下:
@Html.ActionLink("LinkText", "Action", "Controller", new { id = "" }, null)
请注意,我为 id 参数传递了“”,为 HTMLATTRIBUTES 传递了 null。
我需要我的菜单链接是动态的。而不是实行了很多额外的代码和路由与HTML辅助分配每一页我简单。
<a href="@(item.websiteBaseURL)/@(item.controller)/@(item.ViewName)">@item.MenuItemName</a>