46

我认为我有以下 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,因为我的控制器/操作可能会改变。

4

9 回答 9

48

解决方法是指定我自己的路由值(下面的第三个参数)

<%= Html.ActionLink("LinkText", "Action", "Controller", 
    new { id=string.Empty }, null) %>
于 2009-04-23T21:17:57.377 回答
13

听起来您需要注册第二个“仅操作”路由并使用 Html.RouteLink()。首先在您的应用程序启动中注册这样的路由:

routes.MapRoute("ActionOnly", "{controller}/{action}", 
   new { controller = "Home", action = "Index" } );

然后使用 ActionLink 代替创建这些链接:

Html.RouteLink("About","ActionOnly")
于 2010-04-28T14:57:33.987 回答
10

问题是内置方法从您当前所在的 URL 以及您提供的内容中获取输入。你可以试试这个:

<%= Html.ActionLink("LinkText", "Action", "Controller", new { id = ""}) %>

那应该手动擦除 id 参数。

于 2009-04-23T08:38:40.927 回答
4

不知道为什么,但它对我不起作用(可能是因为 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;
        }
于 2010-01-21T13:03:31.740 回答
4

如果您不知道需要显式覆盖哪些值,或者您只是想避免额外的参数列表,您可以使用如下所示的扩展方法。

<a href="@Url.Isolate(u => u.Action("View", "Person"))">View</a>

实现细节在这篇博文中

于 2013-08-21T17:21:08.007 回答
4

我明确地将动作名称设置为“动作/”。看起来有点像黑客,但它是一个快速修复。

@Html.ActionLink("Link Name", "Action/", "Controller")
于 2014-07-30T14:06:07.467 回答
3

另一种方法是使用ActionLink(HtmlHelper, String, String, RouteValueDictionary) 重载,那么就不需要在最后一个参数中放入null

<%= Html.ActionLink("Details", "Details", "Product", new RouteValueDictionary(new { id=item.ID })) %>
于 2010-08-26T13:25:08.857 回答
1

Html.ActionLink 的重载在 MVC 的更高版本上有所更改。在 MVC 5 及更高版本上。这是如何做到这一点:

@Html.ActionLink("LinkText", "Action", "Controller", new { id = "" }, null)

注意我为 id 参数传递了“”,为 HTMLATTRIBUTES 传递了 null。

于 2017-08-14T19:03:39.297 回答
0

我需要我的菜单链接是动态的。我没有为每个页面实现大量额外的代码和路由,而是简单地省去了 HTML 帮助程序。

<a href="@(item.websiteBaseURL)/@(item.controller)/@(item.ViewName)">@item.MenuItemName</a>
于 2014-01-27T22:08:14.080 回答