Vai ir kāda atšķirība starp HTML.ActionLink
un Url.Action
, vai tie ir tikai divi veidi, kā darīt vienu un to pašu?
Kad man vajadzētu dot priekšroku vienam, nevis otram?
Jā, ir atšķirība. Html.ActionLink
ģenerē <a href=".."></a>
birku, bet Url.Action
atgriež tikai url.
Piemēram:
@Html.ActionLink("link text", "someaction", "somecontroller", new { id = "123" }, null)
ģenerē:
<a href="/somecontroller/someaction/123">link text</a>
un Url.Action("someaction", "somecontroller", new { id = "123" })
rada:
/somecontroller/someaction/123
Ir arī Html.Action, kas izpilda pakārtoto kontroliera darbību.
Html.ActionLink
automātiski ģenerē <a href=".."></a>
tagu.
Url.Action
ģenerē tikai url.
Piemēram:
@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)
ģenerē:
<a href="/controllerName/actionName/<id>">link text</a>
un
@Url.Action("actionName", "controllerName", new { id = "<id>" })
ģenerē:
/controllerName/actionName/<id>
Labākais plus punkts, kas man patīk, ir Url.Action(...)
izmantošana.
Jūs pats izveidojat enkura tagu, kurā varat viegli iestatīt savu saistīto tekstu pat ar kādu citu html tagu.
<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">
<img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />
@Html.DisplayFor(model => model.<SomeModelField>)
</a>
<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>
}
Iepriekš minētajā piemērā redzams, ka, ja man ir īpaši nepieciešama poga, lai veiktu kādu darbību, man tas jādara ar @Url.Action, bet, ja es gribu tikai saiti, es izmantošu @Html.ActionLink. Lieta tāda, ka, ja ir jāizmanto kāds elements (HTML) ar darbību, tiek izmantots url.