HTML.ActionLink vs Url.Action in ASP.NET Razor
Is there any difference between HTML.ActionLink
vs Url.Action
or they are just two ways of doing the same thing?
When should I prefer one over the other?
Solution 1:
Yes, there is a difference. Html.ActionLink
generates an <a href=".."></a>
tag whereas Url.Action
returns only an url.
For example:
@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
generates:
<a href="/somecontroller/someaction/123">link text</a>
and Url.Action("someaction", "somecontroller", new { id = "123" })
generates:
/somecontroller/someaction/123
There is also Html.Action which executes a child controller action.
Solution 2:
Html.ActionLink
generates an <a href=".."></a>
tag automatically.
Url.Action
generates only an url.
For example:
@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)
generates:
<a href="/controllerName/actionName/<id>">link text</a>
and
@Url.Action("actionName", "controllerName", new { id = "<id>" })
generates:
/controllerName/actionName/<id>
Best plus point which I like is using Url.Action(...)
You are creating anchor tag by your own where you can set your own linked text easily even with some other html tag.
<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
<img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />
@Html.DisplayFor(model => model.<SomeModelField>)
</a>
Solution 3:
<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>
}
In the above example you can see that If I specifically need a button to do some action, I have to do it with @Url.Action whereas if I just want a link I will use @Html.ActionLink. The point is when you have to use some element(HTML) with action url is used.