liveBook · Manning

Form tag helper

As explained in ASP.NET Core in Action, 3e

The Form Tag Helper is an ASP.NET Core Tag Helper that generates and configures HTML form elements from Razor attributes and routing data.

The Form Tag Helper turns attributes on a Razor <form> element into a submission URL and other HTML. It handles form plumbing so you can concentrate on the fields and what happens when the form is submitted. section 18.2 section 18.2.1

Post a checkout form

Write <form asp-page="Checkout"> around the checkout fields. The generated opening tag is <form action="/Checkout" method="post">. Label, Input, and Validation Message Tag Helpers can then generate field names, labels, and validation markup from the bound PageModel property. section 18.2 section 18.2.1

Use asp-page to post to a particular Razor Page. Without it, the form posts back to the URL that served it—a common choice when the same page displays and handles the form. In that case, write method="post" yourself; otherwise the form defaults to GET, which can be a security risk. section 18.2.1

If the destination page has route parameters, supply their values with asp-route-*, replacing * with the parameter name. For a page whose route is Product/{id}, <form asp-page="Product" asp-route-id="@Model.ProductId"> generates an action such as /Product/5 when ProductId is 5. Route values not used in the path can be passed as query data. The asp-page-handler attribute can also help set the action URL. section 18.2.1 section 18.6

<form action="/Product/5" method="post">

The generated opening tag shows the route value incorporated into the action URL, with POST as the submission method. section 18.2.1

The helper also renders an antiforgery token in a hidden __RequestVerificationToken field and sets a token cookie, unless that protection is disabled. Razor Pages validate the tokens automatically and reject requests with missing or mismatched values. MVC views also receive tokens, but MVC controller actions need [ValidateAntiForgeryToken] to validate them. section 29.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains generated actions, route values, POST defaults, and token validation without implementing routing or token generation.
Examples
Shows a checkout form posting to /Checkout and a Product form inserting an id into /Product/5.
What it assumes
Starts with a Razor Page, a bound PageModel property, and an HTML form, then shows the resulting markup.
What you can do after
Apply it via Razor asp-page and asp-route-* attributes to configure POST destinations and route values.
How it connects
Links Razor Pages, URL generation, route values, HTTP methods, and CSRF protection.

Also explained in

Compare how 2 books explain form tag helper →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.