HTML.ActionLink vs. Url.Action in ASP.NET Razor

Gibt es einen Unterschied zwischen HTML.ActionLink und Url.Action oder sind das nur zwei Möglichkeiten, das Gleiche zu tun?

Wann sollte ich das eine dem anderen vorziehen?

Lösung

Ja, es gibt einen Unterschied. Html.ActionLink erzeugt ein <a href=".."></a> Tag, während Url.Action nur eine URL zurückgibt.

Zum Beispiel:

@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)

erzeugt:

<a href="/somecontroller/someaction/123">link text</a>

und Url.Action("someaction", "somecontroller", new { id = "123" }) erzeugt:

/somecontroller/someaction/123

Es gibt auch eine Html.Action, die eine untergeordnete Controller-Aktion ausführt.

Kommentare (8)

Html.ActionLink erzeugt automatisch ein <a href=".."></a> Tag.

Url.Action erzeugt nur eine Url.

Zum Beispiel:

@Html.ActionLink("link text", "actionName", "controllerName", new { id = "" }, null)

erzeugt:

<a href="/controllerName/actionName/id">link text</a>

und

@Url.Action("actionName", "controllerName", new { id = "" }) 

erzeugt:

/controllerName/actionName/

Der beste Pluspunkt, der mir gefällt, ist die Verwendung von Url.Action(...)

Sie erstellen ein eigenes Anker-Tag, in dem Sie Ihren eigenen verlinkten Text leicht selbst mit einem anderen HTML-Tag setzen können.


<a href="@Url.Action("actionName", "controllerName", new { id = "id" })">
Kommentare (0)
<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>
}

Im obigen Beispiel sehen Sie, dass ich, wenn ich eine Schaltfläche für eine bestimmte Aktion benötige, @Url.Action verwenden muss, während ich, wenn ich nur einen Link möchte, @Html.ActionLink verwenden werde. Der Punkt ist, wenn Sie ein Element (HTML) mit Aktion verwenden müssen, wird url verwendet.

Kommentare (0)