liveBook · Manning

Asp-action attribute

As explained in Pro ASP.NET Core 7, Tenth Edition

The asp-action attribute is a Razor tag helper attribute that identifies the action method for which a URL should be generated.

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

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains rendered href and action attributes, controller defaults, route values, and routing changes without descending into tag-helper internals.
Examples
Uses RSVP navigation, an RSVP form, and product-selection links carrying ProductId route values.
What it assumes
Assumes basic Razor views, controllers, action methods, and application routing while demonstrating tag-helper behavior through rendered markup.
What you can do after
Apply it to generate routing-aware links and form destinations without hard-coding URL formats.
How it connects
Connects Razor tag helpers with action methods, controllers, URL routing, forms, and Razor views.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.