The asp-action attribute is a Razor tag helper instruction that generates a URL for a named action method instead of requiring a hard-coded path. On an anchor, it produces href; on a form, it produces action. Without asp-controller, the target is the controller that rendered the current view. section 3.2.4 section 3.2.5 section 26.3
Use the attribute where view markup needs to target an action:
- Link to another action on the current controller with <a asp-action="RsvpForm">RSVP Now</a>. section 3.2.4
- Submit a form to an action with <form asp-action="RsvpForm" method="post">. section 3.2.5
- Combine asp-action with asp-controller when the destination belongs to another controller. section 26.3
- Supply route parameters through asp-route-[name], such as asp-route-id, when the action requires a segment value. section 26.3
Generated URLs in a party application
An Index view can use <a asp-action="RsvpForm">RSVP Now</a>, which renders a link such as /Home/RsvpForm. The RSVP form can use <form asp-action="RsvpForm" method="post">, which renders an action such as /Home/RsvpForm. If routing conventions change, both generated URLs change with them; the view markup does not need manual path edits. section 3.2.4 section 3.2.5
Listing 26.7 Transforming an element in the Views/Home/_RowPartial.cshtml file
@model Product
<tr>
<td>@Model.Name</td>
<td>@Model.Price.ToString("c")</td>
<td>@Model.CategoryId</td>
<td>@Model.SupplierId</td>
<td>
<a asp-action="index" asp-controller="home"
asp-route-id="@Model?.ProductId"
class="btn btn-sm btn-info text-white">
Select
</a>
</td>
</tr>
A realistic partial view combines asp-action, asp-controller, and asp-route-id to create a selectable product link. section 26.3
