如何使剃刀动作链接在新标签页中打开?

81

我想让我的链接在新标签页中打开(必须使用razor格式):

    <a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() }, new { target = "_blank" })" type="submit" id="runReport" class="button Secondary">@Reports.RunReport</a>

不过这并没有起作用。有人知道如何做吗?


6
为什么你要费心将那个东西放到 Url.Action 里面呢?直接把它放到 <a> 标签里就好了。 - Joel Etherton
10个回答

137

只需使用 HtmlHelper 中的 ActionLink 方法,并相应地设置 RouteValuesHtmlAttributes

@Html.ActionLink(Reports.RunReport, "RunReport", new { controller = "Performance", reportView = Model.ReportView.ToString() }, new { target = "_blank" })

47
看起来你将 Html.ActionLink()Url.Action() 混淆了。Url.Action没有设置目标的参数,因为它只返回一个URL。
基于你当前的代码,锚文本应该像这样:
<a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })" 
   type="submit" 
   id="runReport" 
   target="_blank"
   class="button Secondary">
     @Reports.RunReport
</a>

23

由于UrlHelper.Action(string,string,object,object)不存在,所以它不会编译通过。

UrlHelper.Action只会生成基于提供的操作的Url,而不是基于<a>标记。如果你想添加一个Html属性(比如target="_blank",在新标签页中打开链接),你可以选择:


18
如果您的目标是使用ActionLink辅助函数并在新标签页中打开链接:
@Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })

@Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})

9
@Html.ActionLink(
"Pay Now",
"Add",
"Payment",
new { @id = 1 },htmlAttributes:new { @class="btn btn-success",@target= "_blank" } )

2
虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - Alex Riabov

7

For

@Url.Action

<a href="@Url.Action("Action", "Controller")" target="_blank">Link Text</a>

7
使用命名参数:
@Html.ActionLink(linkText: "TestTab", actionName: "TestAction", controllerName: "TestController", routeValues: null, htmlAttributes: new { target = "_blank"})

1

asp.net mvc ActionLink新标签页与angular参数

<a  target="_blank" class="btn" data-ng-href="@Url.Action("RunReport", "Performance")?hotelCode={{hotel.code}}">Select Room</a>

0

<a href="@Url.Action("RunReport", "Performance", new { reportView = Model.ReportView.ToString() })" type="submit" id="runReport" target="_blank" class="button Secondary"> @Reports.RunReport </a>

的翻译内容如下:

0

你将它的 type 设置为 submit。这意味着浏览器应该将你的 <form> 数据提交到服务器。

实际上,根据w3schools的说法,标签没有 type 属性。

因此,请移除 remote 的 type 属性,这样就可以正常工作了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接