Reading some tutorials of ASP.NET MVC I found these two helpers being used to do basically the same thing, which was to direct the user to a new view.
That’s not what they do. Their function is to generate links based on the routes defined in the configuration of your application. Redirection is done in controller, using RedirectToAction()
.
So I wonder if there’s any more remarkable difference between HTML.ActionLink
and Url.Action
?
@Html.ActionLink()
generates a tag <a>
with a simple text inside and some configuration, such as the controller, as tokens route and some HTML configuration, such as class
, id
, etc..
@Url.Action
allows you to assemble your logic (which need not necessarily be a tag <a>
) using the link generated according to the route. A very common case is that you want to create buttons with icons inside and want to create a link to the set:
<a href="@Url.Action("MinhaAction", "MeuController")">
<div class="meu-botao">
<img src="@Url.Content("~/Images/minha-imagem.jpg")" />
Um texto dentro do botão
</div>
</a>
What are the necessary conditions to use one instead of the other ?
The goal. If the idea is just a text link (which you can even style in the form of a button using CSS), @Html.ActionLink()
meets well. If the idea is to assemble a more complex link, with image inside, text or other components, @Url.Action()
better.