What is Difference Between HTML.ActionLink vs. Url.Action?

10

Reading some tutorials from 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 .

Then I would like to know if there is any more noticeable difference between HTML.ActionLink and Url.Action ?

What are the conditions necessary to use one instead of the other?

    
asked by anonymous 28.03.2017 / 17:24

3 answers

10
  

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.

    
28.03.2017 / 18:57
13

Well, HTML.ActionLink %% generates a <a href="..."></a> as Url.Action returns the url

For example:

@Html.ActionLink("Link", "action", "controller", new { id = "123" }, null)

Generates:

<a href="/controller/action/123">Link</a>

while:

Url.Action("action", "controller", new { id = "123" })

Generates:

/controller/action/123

Source (English)

    
28.03.2017 / 17:30
4

One generates an tag HTML with a full link , the other generates only one (partial) URL:

28.03.2017 / 17:31