ASP.NET Razor中的HTML.ActionLink与Url.Action

HTML.ActionLink vs Url.Action in ASP.NET Razor

HTML.ActionLink vs Url.Action之间有什么区别,或者它们只是两种做同样事情的方法吗?

我什么时候应该更喜欢一个?


是,有一点不同。 Html.ActionLink生成标记,而Url.Action仅返回网址。

例如:

1
@Html.ActionLink("link text","someaction","somecontroller", new { id ="123" }, null)

产生:

1
link text

并且Url.Action("someaction","somecontroller", new { id ="123" })生成:

1
/somecontroller/someaction/123

还有Html.Action执行子控制器操作。


Html.ActionLink自动生成标记。

Url.Action仅生成网址。

例如:

1
@Html.ActionLink("link text","actionName","controllerName", new { id ="<id>" }, null)

产生:

1
">link text

1
@Url.Action("actionName","controllerName", new { id ="<id>" })

产生:

1
/controllerName/actionName/<id>

我喜欢的最佳加点是使用Url.Action(...)

您正在创建自己的锚标记,您可以轻松地设置自己的链接文本,甚至可以使用其他一些html标记。

1
2
3
4
5
" })">

   <img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />

   @Html.DisplayFor(model => model.<SomeModelField>)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<p>

    @Html.ActionLink("Create New","Create")

</p>
@using (Html.BeginForm("Index","Company", FormMethod.Get))
{
    <p>

        Find by Name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
        <input type="button" value="Clear" onclick="location.href='@Url.Action("Index","Company")'"/>
   
</p>
}

在上面的例子中,您可以看到如果我特别需要一个按钮来执行某些操作,我必须使用@ Url.Action,而如果我只想要一个链接,我将使用@ Html.ActionLink。
关键是当你必须使用一些元素(HTML)时,使用动作url。


@HTML.ActionLink生成HTML anchor tag。而@Url.Action为您生成URL。你可以很容易地理解它;

1
2
3
4
5
6
7
8
// 1. Item Definition
@HTML.ActionLink("Item Definition","ActionMethod","ControllerName")

// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod","ControllerName")

// 3. Item Definition
 Item Definition

这两种方法都不同,完全取决于您的需求。


您可以使用适当的CSS样式轻松地将Html.ActionLink作为按钮呈现。
例如:

1
@Html.ActionLink("Save","ActionMethod","Controller", new { @class ="btn btn-primary" })


我使用下面的代码创建一个Button,它对我有用。

1
<input type="button" value="PDF" onclick="location.href='@Url.Action("Export","tblOrder")'"/>