27 Using the forms tag helpers

 

This chapter covers

  • Using ASP.NET Core tag helpers to transform form elements
  • Transforming input elements and formatting their contents
  • Generating label elements from model properties
  • Generating select and option elements
  • Protecting forms against cross-site request forgery

In this chapter, I describe the built-in tag helpers that are used to create HTML forms. These tag helpers ensure forms are submitted to the correct action or page handler method and that elements accurately represent specific model properties. Table 27.1 puts the form tag helpers in context.

Table 27.1 Putting form tag helpers in context (view table figure)

Question

Answer

What are they?

These built-in tag helpers transform HTML form elements.

Why are they useful?

These tag helpers ensure that HTML forms reflect the application’s routing configuration and data model.

How are they used?

Tag helpers are applied to HTML elements using asp-* attributes.

Are there any pitfalls or limitations?

These tag helpers are reliable and predictable and present no serious issues.

Are there any alternatives?

You don’t have to use tag helpers and can define forms without them if you prefer.

Table 27.2 provides a guide to the chapter.

27.1 Preparing for this chapter

27.1.1 Dropping the database

27.1.2 Running the example application

27.2 Understanding the form handling pattern

27.2.1 Creating a controller to handle forms

27.2.2 Creating a Razor Page to handle forms

27.3 Using tag helpers to improve HTML forms

27.3.1 Working with form elements

27.3.2 Transforming form buttons

27.4 Working with input elements

27.4.1 Transforming the input element type attribute

27.4.2 Formatting input element values

27.4.3 Displaying values from related data in input elements

27.5 Working with label elements

27.6 Working with select and option elements

26.6.1 Populating a select element