25 Using tag helpers

 

This chapter covers

  • Transforming HTML elements using tag helpers
  • Receiving context data in a tag helper class
  • Registering and applying tag helpers
  • Selecting elements to transform with tag helper scope
  • Creating custom shorthand elements
  • Generating content for view model properties
  • Creating tag helpers that can be consumed through dependency injection

Tag helpers are C# classes that transform HTML elements in a view or page. Common uses for tag helpers include generating URLs for forms using the application’s routing configuration, ensuring that elements of a specific type are styled consistently, and replacing custom shorthand elements with commonly used fragments of content. In this chapter, I describe how tag helpers work and how custom tag helpers are created and applied. In chapter 26, I describe the built-in tag helpers, and in chapter 27, I use tag helpers to explain how HTML forms are created. Table 25.1 puts tag helpers in context.

25.1 Preparing for this chapter

25.1.1 Dropping the database

25.1.2 Running the example application

25.2 Creating a tag helper

25.2.1 Defining the tag helper class

25.2.2 Registering tag helpers

25.2.3 Using a tag helper

25.2.4 Narrowing the scope of a tag helper

25.2.5 Widening the scope of a tag helper

25.3 Advanced tag helper features

25.3.1 Creating shorthand elements

25.3.2 Creating elements programmatically

25.3.3 Prepending and appending content and elements

25.3.4 Getting view context data

25.3.5 Working with model expressions

25.3.6 Coordinating between tag helpers

25.3.7 Suppressing the output element

25.4 Using tag helper components

25.4.1 Creating a tag helper component

25.4.2 Expanding tag helper component element selection

Summary