HTML.ActionLink vs Url.Action in ASP.NET Razor
我什么时候应该更喜欢一个?
是,有一点不同。
例如:
1 | @Html.ActionLink("link text","someaction","somecontroller", new { id ="123" }, null) |
产生:
1 | link text |
并且
1 | /somecontroller/someaction/123 |
还有Html.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> |
我喜欢的最佳加点是使用
您正在创建自己的锚标记,您可以轻松地设置自己的链接文本,甚至可以使用其他一些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。
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")'"/> |