Reading some ASP.NET MVC tutorials 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 job is to generate links based on the routes defined in your application's configuration. Redirection is done in controller , using RedirectToAction()
".
Then I would like to know if there is any more noticeable difference between HTML.ActionLink
and Url.Action
?
@Html.ActionLink()
generates a tag <a>
with simple text inside and some configuration, such as controller , route tokens and some HTML configuration, such as class
, id
, etc.
@Url.Action
allows you to mount 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 conditions necessary to use one instead of the other?
The goal. If the idea is just a link with text (which you can even style in the form of a button using CSS), @Html.ActionLink()
caters well. If the idea is to mount a more complex link, with image inside, text or other components, @Url.Action()
is better.