HTML.ActionLink
与Url.Action
之间有什么区别吗,或者它们只是做同样事情的两种方式?
什么时候我应该选择一个而不是另一个?
是的,有区别。Html.ActionLink
生成一个<a href="."></a>
标签,而Url.Action
只返回一个网址。
比如说。
@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
产生了。
<a href="/somecontroller/someaction/123">link text</a>
而Url.Action("someaction", "somecontroller", new { id = "123" })
会产生。
/somecontroller/someaction/123
还有Html.Action可以执行一个子控制器动作。
Html.ActionLink
会自动生成一个<a href="."></a>
标签。
Url.Action
只生成一个网址。
比如说。
@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)
产生了。
<a href="/controllerName/actionName/<id>">link text</a>
和
@Url.Action("actionName", "controllerName", new { id = "<id>" })
产生。
/controllerName/actionName/<id>
我喜欢的最佳加分项是使用Url.Action(...)
。
你正在自己创建锚标签,在那里你可以很容易地设置你自己的链接文本,甚至与一些其他的HTML标签。
<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
<img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />
@Html.DisplayFor(model => model.<SomeModelField>)
</a>
<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锚标签
。
而"@Url.Action "则为你生成一个 "URL"。
你可以很容易理解。
// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")
// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")
// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>
这两种方法都是不同的,完全取决于你的需求。
你可以通过使用适当的CSS样式轻松地将Html.ActionLink呈现为一个按钮。 例如:
@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })
}
@Html.ActionLink("Save", "ActionMethod", "Controller", new { @class = "btn btn-primary" })