What is the Difference Between HTML.Actionlink vs Url.Action?

Asked

Viewed 17,994 times

11

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.

So I wonder if there’s any more remarkable difference between HTML.ActionLink and Url.Action?

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

3 answers

15

Well, the HTML.ActionLink generates a <a href="..."></a> while 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 (in English)

13


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.

3

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

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

Produces:

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

Already

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

Produces only:

/controller/action/123

I put in the Github for future reference.

Source.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.