liveBook · Manning

Asp-page attribute

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

The asp-page attribute is an ASP.NET Core tag helper attribute that identifies the Razor Page used when generating a form submission URL.

The asp-page attribute is a built-in ASP.NET Core tag helper attribute for selecting a Razor Page as a generated navigation or form-submission target. The routing system converts the page name into the rendered href or action URL, so route configuration changes are reflected automatically. section 26.3.1 section 27.3.1

Use asp-page with the surrounding tag-helper attributes when the target is a Razor Page:

  • Set asp-page on an anchor to generate its href, using a page path such as /suppliers/list. section 26.3.1
  • Set asp-page on a form to generate its action URL; specify method explicitly when the form should submit with POST. section 27.3.1
  • Use asp-page-handler to select a handler method and asp-route-* attributes to supply route values. section 26.3.1 section 27.3.1
  • Apply asp-page to a button outside its form when the button uses form to identify the form being submitted. section 27.3.2

Targeting a Razor Page from a form

A form such as <form asp-page="FormHandler" method="post"> is rendered with an action targeting /pages/form. The same attribute can be placed on an external button, where the tag helper generates the button's formaction. section 27.3.1 section 27.3.2

Listing 27.11 Setting the form target in the FormHandler.cshtml file in the Pages folder
...
<div class="m-2">
    <h5 class="bg-primary text-white text-center p-2">HTML Form</h5>
    <form asp-page="FormHandler" method="post">
        <div class="form-group">
            <label>Name</label>
            <input class="form-control" name="Name" 
                value="@Model.Product?.Name" />
        </div>
        <button type="submit" class="btn btn-primary mt-2">Submit</button>
    </form>
</div>
...

Inspect a complete Razor Page form using asp-page, an explicit POST method, model-bound input, and a submit button. section 27.3.1

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

How deep it goes
Explains target selection, route generation, rendered HTML, and related attributes, while deferring non-element URL generation to Url.Page.
Examples
Uses Suppliers links, FormHandler forms, shared product-editor partials, and buttons outside forms.
What it assumes
Uses Razor Pages, HTML forms, routing, and built-in tag-helper syntax as surrounding mechanisms.
What you can do after
Operate/configure links and forms to target named Razor Pages while verifying the rendered href, action, or formaction.
How it connects
Connects Razor Pages with tag helpers, routing, form submission, anchor elements, asp-page-handler, and asp-route-* values.

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.