.NET Core + ASP.NET Core Training Course
Session 12
.NET Core
What we learned?
Session 6 ~ 11 Overview
• ASP.NET Core Basics
• Middleware, Controllers, Action Filters and Routing
• Models
• Views
.NET Core
What we’ll learn today?
Session 12 Agenda
• Views
.NET Core
Introduction to Tag Helpers
Views – Tag Helpers
What are Tag Helpers?
Tag Helpers enable server-side code to participate in creating and rendering HTML
elements in Razor files.
For example, the built-in ImageTagHelper can append a version number to the
image name. Whenever the image changes, the server generates a new unique
version for the image, so clients are guaranteed to get the current image (instead of
a stale cached image).
.NET Core
Introduction to Tag Helpers
Views – Tag Helpers
What Tag Helpers provide?
An HTML-friendly development experience
For the most part, Razor markup using Tag Helpers looks like standard HTML. Front-
end designers conversant with HTML/CSS/JavaScript can edit Razor without
learning C# Razor syntax.
A rich IntelliSense environment for creating HTML and Razor markup
This is in sharp contrast to HTML Helpers, the previous approach to server-side
creation of markup in Razor views.
.NET Core
Managing Tag Helper scope
Views – Tag Helpers
Tag Helpers scope is controlled by a combination of @addTagHelper,
@removeTagHelper, and the ”!” opt-out character.
@addTagHelper makes Tag Helpers available
In Views/_ViewImports.cshtml:
@using AuthoringTagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
.NET Core
Managing Tag Helper scope
Views – Tag Helpers
The @addTagHelper directive makes Tag Helpers available to the view. In this case,
the view file is Views/_ViewImports.cshtml, which by default is inherited by all view
files in the Views folder and sub-directories; making Tag Helpers available.
The code above uses the wildcard syntax (“*”) to specify that all Tag Helpers in the
specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers) will be available to every
view file in the Views directory or sub-directory.
.NET Core
Managing Tag Helper scope
Views – Tag Helpers
The first parameter after @addTagHelper specifies the Tag Helpers to load (we are
using “*” for all Tag Helpers), and the second parameter
“Microsoft.AspNetCore.Mvc.TagHelpers” specifies the assembly containing the Tag
Helpers. Microsoft.AspNetCore.Mvc.TagHelpers is the assembly for the built-in
ASP.NET Core Tag Helpers.
.NET Core
Using Tag Helpes
Views – Tag Helpers
To add a Tag Helper to a view using an FQN, you first add the FQN
(AuthoringTagHelpers.TagHelpers.EmailTagHelper), and then the assembly name
(AuthoringTagHelpers). Most developers prefer to use the “*” wildcard syntax. The
wildcard syntax allows you to insert the wildcard character “*” as the suffix in an
FQN. For example, any of the following directives will bring in the EmailTagHelper:
@addTagHelper "AuthoringTagHelpers.TagHelpers.E*, AuthoringTagHelpers"
@addTagHelper "AuthoringTagHelpers.TagHelpers.Email*, AuthoringTagHelpers"
.NET Core
Using Tag Helpes
Views – Tag Helpers
@removeTagHelper removes Tag Helpers
The @removeTagHelper has the same two parameters as @addTagHelper, and it
removes a Tag Helper that was previously added. For example, @removeTagHelper
applied to a specific view removes the specified Tag Helper from the view.
Using @removeTagHelper in a Views/Folder/_ViewImports.cshtml file removes the
specified Tag Helper from all of the views in Folder.
.NET Core
Controlling Tag Helper scope with the _ViewImports.cshtml file
Views – Tag Helpers
You can add a _ViewImports.cshtml to any view folder, and the view engine adds
the directives from that _ViewImports.cshtml file to those contained in the
Views/_ViewImports.cshtml file. If you added an empty
Views/Home/_ViewImports.cshtml file for the Home views, there would be no
change because the _ViewImports.cshtml file is additive.
.NET Core
Opting out of individual elements
Views – Tag Helpers
You can disable a Tag Helper at the element level with the Tag Helper opt-out
character (”!”). For example, Email validation is disabled in the <span> with the Tag
Helper opt-out character:
<!span asp-validation-for="Email" class="text-danger"></!span>
You must apply the Tag Helper opt-out character to the opening and closing tag. (The
Visual Studio editor automatically adds the opt-out character to the closing tag when
you add one to the opening tag). After you add the opt-out character, the element
and Tag Helper attributes are no longer displayed in a distinctive font.
.NET Core
Using @tagHelperPrefix to make Tag Helper usage explicit
Views – Tag Helpers
The @tagHelperPrefix directive allows you to specify a tag prefix string to enable Tag
Helper support and to make Tag Helper usage explicit. In the code image below, the Tag
Helper prefix is set to th:, so only those elements using the prefix th: support Tag Helpers
(Tag Helper-enabled elements have a distinctive font). The <label> and <input> elements
have the Tag Helper prefix and are Tag Helper-enabled, while the <span> element does not.
.NET Core
IntelliSense support for Tag Helpers
Views – Tag Helpers
When you create a new ASP.NET web app in Visual Studio, it adds
“Microsoft.AspNetCore.Razor.Tools” to the project.json file. This is the package that adds
Tag Helper tooling.
Consider writing an HTML <label> element. As soon as you enter <l in the Visual Studio
editor, IntelliSense displays matching elements:
.NET Core
IntelliSense support for Tag Helpers
Views – Tag Helpers
identifies the element as targeted by Tag Helpers. Pure HTML elements (such as the
fieldset) display the “<>”icon.
A pure HTML <label> tag displays the HTML tag (with the default Visual Studio color theme)
in a brown font, the attributes in red, and the attribute values in blue.
IntelliSense displays all the methods and properties on the page model.
.NET Core
Tag Helpers compared to HTML Helpers
Views – Tag Helpers
Tag Helpers attach to HTML elements in Razor views, while HTML Helpers are invoked as
methods interspersed with HTML in Razor views. Consider the following Razor markup,
which creates an HTML label with the CSS class “caption”:
@Html.Label("FirstName", "First Name:", new {@class="caption"})
The at (@) symbol tells Razor this is the start of code. The next two parameters (“FirstName”
and “First Name:”) are strings, so IntelliSense can’t help. The last argument:
new {@class="caption"}
Is an anonymous object used to represent attributes. Because class is a reserved keyword in
C#, you use the @ symbol to force C# to interpret “@class=” as a symbol (property name).
.NET Core
Tag Helpers compared to HTML Helpers
Views – Tag Helpers
Tag Helpers attach to HTML elements in Razor views, while HTML Helpers are invoked as
methods interspersed with HTML in Razor views. Consider the following Razor markup,
which creates an HTML label with the CSS class “caption”:
@Html.Label("FirstName", "First Name:", new {@class="caption"})
The at (@) symbol tells Razor this is the start of code. The next two parameters (“FirstName”
and “First Name:”) are strings, so IntelliSense can’t help. The last argument:
new {@class="caption"}
Is an anonymous object used to represent attributes. Because class is a reserved keyword in
C#, you use the @ symbol to force C# to interpret “@class=” as a symbol (property name).
.NET Core
HTML Helpers
Views – Tag Helpers
.NET Core
Tag Helpers
Views – Tag Helpers
.NET Core
Tag Helpers compared to Web Server Controls
Views – Tag Helpers
• Tag Helpers don’t own the element they’re associated with; they simply participate in the
rendering of the element and content. ASP.NET Web Server controls are declared and
invoked on a page.
• Web Server controls have a non-trivial lifecycle that can make developing and
debugging difficult.
• Web Server controls allow you to add functionality to the client Document Object Model
(DOM) elements by using a client control. Tag Helpers have no DOM.
• Web Server controls include automatic browser detection. Tag Helpers have no
knowledge of the browser.
.NET Core
Tag Helpers compared to Web Server Controls
Views – Tag Helpers
• Multiple Tag Helpers can act on the same element (see Avoiding Tag Helper conflicts )
while you typically can’t compose Web Server controls.
• Tag Helpers can modify the tag and content of HTML elements that they’re scoped to,
but don’t directly modify anything else on a page. Web Server controls have a less
specific scope and can perform actions that affect other parts of your page; enabling
unintended side effects.
• Web Server controls use type converters to convert strings into objects. With Tag
Helpers, you work natively in C#, so you don’t need to do type conversion.
.NET Core
Customizing the Tag
Helper element font
Views – Tag Helpers
.NET Core
Authoring Tag Helpers
Views – Tag Helpers
A tag helper is any class that implements the ITagHelper interface. However, when you author
a tag helper, you generally derive from TagHelper, doing so gives you access to the Process
method.
Create a folder to hold the Tag Helpers called TagHelpers. The TagHelpers folder is not
required, but it is a reasonable convention.
.NET Core
Authoring Tag Helpers – Sample Email Helper
Views – Tag Helpers
<email>Support</email>  <a href="mailto:Support@contoso.com">Support@contoso.com</a>
.NET Core
Authoring Tag Helpers – Sample Email Helper
Views – Tag Helpers
• The EmailTagHelper class derives from TagHelper. The TagHelper class provides methods
and properties for writing Tag Helpers.
• The overridden Process method controls what the tag helper does when executed. The
TagHelper class also provides an asynchronous version (ProcessAsync) with the same
parameters.
• The context parameter to Process (and ProcessAsync) contains information associated with
the execution of the current HTML tag.
• The output parameter to Process (and ProcessAsync) contains a stateful HTML element
representative of the original source used to generate an HTML tag and content.
.NET Core
Authoring Tag Helpers – Sample Email Helper
Views – Tag Helpers
To make the EmailTagHelper class available to all our Razor views, we will add the
addTagHelper directive to the Views/_ViewImports.cshtml file:
@using AuthoringTagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper "AuthoringTagHelpers.TagHelpers.EmailTagHelper, AuthoringTagHelpers“
<address>
<strong>Support:</strong><email>Support</email><br />
<strong>Marketing:</strong><email>Marketing</email>
</address>
.NET Core
Authoring Tag Helpers – Sample Email Helper
Views – Tag Helpers
.NET Core
Authoring Tag Helpers – Sample Email Helper
Views – Tag Helpers
<address>
<strong>Support:</strong><email mail-to="Support"></email><br />
<strong>Marketing:</strong><email mail-to="Marketing"></email>
</address>
Note: If you were to write the email tag self-closing (<email mail-to="Rick" />), the final output
would also be self-closing. To enable the ability to write the tag with only a start tag (<email mail-
to="Rick">) you must decorate the class with the following:
.NET Core
Authoring Tag Helpers – Sample Email Helper
Views – Tag Helpers
With a self-closing email tag helper, the output would be <a href="mailto:Rick@contoso.com" />.
Self-closing anchor tags are not valid HTML, so you wouldn’t want to create one, but you might want
to create a tag helper that is self-closing. Tag helpers set the type of the TagMode property after
reading a tag.
.NET Core
Authoring Tag Helpers – Sample Email Helper
Views – Tag Helpers
An asynchronous email helper
.NET Core
Authoring Tag Helpers – Sample Bold Helper
Views – Tag Helpers
[HtmlTargetElement("bold", Attributes = "bold")]
.NET Core
Authoring Tag Helpers – Web site information Helper
Views – Tag Helpers
.NET Core
Authoring Tag
Helpers – Web site
information Helper
Views – Tag Helpers
.NET Core
Authoring Tag
Helpers – Web site
information Helper
Views – Tag Helpers
.NET Core
Note
Views – Tag Helpers
Tag helpers translates Pascal-cased C# class names and properties for tag helpers into
lower kebab case. Therefore, to use the WebsiteInformationTagHelper in Razor, you’ll
write <website-information />.
We are not explicitly identifying the target element with the [HtmlTargetElement]
attribute, so the default of website-information will be targeted. If you applied the
following attribute (note it’s not kebab case but matches the class name):
[HtmlTargetElement("WebsiteInformation")]
.NET Core
Note
Views – Tag Helpers
The lower kebab case tag <website-information /> would not match. If you want use
the [HtmlTargetElement] attribute, you would use kebab case as shown below:
[HtmlTargetElement("Website-Information")]
.NET Core
Note
Views – Tag Helpers
The lower kebab case tag <website-information /> would not match. If you want use
the [HtmlTargetElement] attribute, you would use kebab case as shown below:
[HtmlTargetElement("Website-Information")]
.NET Core
Demo
Demo

.NET Core, ASP.NET Core Course, Session 12

  • 1.
    .NET Core +ASP.NET Core Training Course Session 12
  • 2.
    .NET Core What welearned? Session 6 ~ 11 Overview • ASP.NET Core Basics • Middleware, Controllers, Action Filters and Routing • Models • Views
  • 3.
    .NET Core What we’lllearn today? Session 12 Agenda • Views
  • 4.
    .NET Core Introduction toTag Helpers Views – Tag Helpers What are Tag Helpers? Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. For example, the built-in ImageTagHelper can append a version number to the image name. Whenever the image changes, the server generates a new unique version for the image, so clients are guaranteed to get the current image (instead of a stale cached image).
  • 5.
    .NET Core Introduction toTag Helpers Views – Tag Helpers What Tag Helpers provide? An HTML-friendly development experience For the most part, Razor markup using Tag Helpers looks like standard HTML. Front- end designers conversant with HTML/CSS/JavaScript can edit Razor without learning C# Razor syntax. A rich IntelliSense environment for creating HTML and Razor markup This is in sharp contrast to HTML Helpers, the previous approach to server-side creation of markup in Razor views.
  • 6.
    .NET Core Managing TagHelper scope Views – Tag Helpers Tag Helpers scope is controlled by a combination of @addTagHelper, @removeTagHelper, and the ”!” opt-out character. @addTagHelper makes Tag Helpers available In Views/_ViewImports.cshtml: @using AuthoringTagHelpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
  • 7.
    .NET Core Managing TagHelper scope Views – Tag Helpers The @addTagHelper directive makes Tag Helpers available to the view. In this case, the view file is Views/_ViewImports.cshtml, which by default is inherited by all view files in the Views folder and sub-directories; making Tag Helpers available. The code above uses the wildcard syntax (“*”) to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers) will be available to every view file in the Views directory or sub-directory.
  • 8.
    .NET Core Managing TagHelper scope Views – Tag Helpers The first parameter after @addTagHelper specifies the Tag Helpers to load (we are using “*” for all Tag Helpers), and the second parameter “Microsoft.AspNetCore.Mvc.TagHelpers” specifies the assembly containing the Tag Helpers. Microsoft.AspNetCore.Mvc.TagHelpers is the assembly for the built-in ASP.NET Core Tag Helpers.
  • 9.
    .NET Core Using TagHelpes Views – Tag Helpers To add a Tag Helper to a view using an FQN, you first add the FQN (AuthoringTagHelpers.TagHelpers.EmailTagHelper), and then the assembly name (AuthoringTagHelpers). Most developers prefer to use the “*” wildcard syntax. The wildcard syntax allows you to insert the wildcard character “*” as the suffix in an FQN. For example, any of the following directives will bring in the EmailTagHelper: @addTagHelper "AuthoringTagHelpers.TagHelpers.E*, AuthoringTagHelpers" @addTagHelper "AuthoringTagHelpers.TagHelpers.Email*, AuthoringTagHelpers"
  • 10.
    .NET Core Using TagHelpes Views – Tag Helpers @removeTagHelper removes Tag Helpers The @removeTagHelper has the same two parameters as @addTagHelper, and it removes a Tag Helper that was previously added. For example, @removeTagHelper applied to a specific view removes the specified Tag Helper from the view. Using @removeTagHelper in a Views/Folder/_ViewImports.cshtml file removes the specified Tag Helper from all of the views in Folder.
  • 11.
    .NET Core Controlling TagHelper scope with the _ViewImports.cshtml file Views – Tag Helpers You can add a _ViewImports.cshtml to any view folder, and the view engine adds the directives from that _ViewImports.cshtml file to those contained in the Views/_ViewImports.cshtml file. If you added an empty Views/Home/_ViewImports.cshtml file for the Home views, there would be no change because the _ViewImports.cshtml file is additive.
  • 12.
    .NET Core Opting outof individual elements Views – Tag Helpers You can disable a Tag Helper at the element level with the Tag Helper opt-out character (”!”). For example, Email validation is disabled in the <span> with the Tag Helper opt-out character: <!span asp-validation-for="Email" class="text-danger"></!span> You must apply the Tag Helper opt-out character to the opening and closing tag. (The Visual Studio editor automatically adds the opt-out character to the closing tag when you add one to the opening tag). After you add the opt-out character, the element and Tag Helper attributes are no longer displayed in a distinctive font.
  • 13.
    .NET Core Using @tagHelperPrefixto make Tag Helper usage explicit Views – Tag Helpers The @tagHelperPrefix directive allows you to specify a tag prefix string to enable Tag Helper support and to make Tag Helper usage explicit. In the code image below, the Tag Helper prefix is set to th:, so only those elements using the prefix th: support Tag Helpers (Tag Helper-enabled elements have a distinctive font). The <label> and <input> elements have the Tag Helper prefix and are Tag Helper-enabled, while the <span> element does not.
  • 14.
    .NET Core IntelliSense supportfor Tag Helpers Views – Tag Helpers When you create a new ASP.NET web app in Visual Studio, it adds “Microsoft.AspNetCore.Razor.Tools” to the project.json file. This is the package that adds Tag Helper tooling. Consider writing an HTML <label> element. As soon as you enter <l in the Visual Studio editor, IntelliSense displays matching elements:
  • 15.
    .NET Core IntelliSense supportfor Tag Helpers Views – Tag Helpers identifies the element as targeted by Tag Helpers. Pure HTML elements (such as the fieldset) display the “<>”icon. A pure HTML <label> tag displays the HTML tag (with the default Visual Studio color theme) in a brown font, the attributes in red, and the attribute values in blue. IntelliSense displays all the methods and properties on the page model.
  • 16.
    .NET Core Tag Helperscompared to HTML Helpers Views – Tag Helpers Tag Helpers attach to HTML elements in Razor views, while HTML Helpers are invoked as methods interspersed with HTML in Razor views. Consider the following Razor markup, which creates an HTML label with the CSS class “caption”: @Html.Label("FirstName", "First Name:", new {@class="caption"}) The at (@) symbol tells Razor this is the start of code. The next two parameters (“FirstName” and “First Name:”) are strings, so IntelliSense can’t help. The last argument: new {@class="caption"} Is an anonymous object used to represent attributes. Because class is a reserved keyword in C#, you use the @ symbol to force C# to interpret “@class=” as a symbol (property name).
  • 17.
    .NET Core Tag Helperscompared to HTML Helpers Views – Tag Helpers Tag Helpers attach to HTML elements in Razor views, while HTML Helpers are invoked as methods interspersed with HTML in Razor views. Consider the following Razor markup, which creates an HTML label with the CSS class “caption”: @Html.Label("FirstName", "First Name:", new {@class="caption"}) The at (@) symbol tells Razor this is the start of code. The next two parameters (“FirstName” and “First Name:”) are strings, so IntelliSense can’t help. The last argument: new {@class="caption"} Is an anonymous object used to represent attributes. Because class is a reserved keyword in C#, you use the @ symbol to force C# to interpret “@class=” as a symbol (property name).
  • 18.
  • 19.
  • 20.
    .NET Core Tag Helperscompared to Web Server Controls Views – Tag Helpers • Tag Helpers don’t own the element they’re associated with; they simply participate in the rendering of the element and content. ASP.NET Web Server controls are declared and invoked on a page. • Web Server controls have a non-trivial lifecycle that can make developing and debugging difficult. • Web Server controls allow you to add functionality to the client Document Object Model (DOM) elements by using a client control. Tag Helpers have no DOM. • Web Server controls include automatic browser detection. Tag Helpers have no knowledge of the browser.
  • 21.
    .NET Core Tag Helperscompared to Web Server Controls Views – Tag Helpers • Multiple Tag Helpers can act on the same element (see Avoiding Tag Helper conflicts ) while you typically can’t compose Web Server controls. • Tag Helpers can modify the tag and content of HTML elements that they’re scoped to, but don’t directly modify anything else on a page. Web Server controls have a less specific scope and can perform actions that affect other parts of your page; enabling unintended side effects. • Web Server controls use type converters to convert strings into objects. With Tag Helpers, you work natively in C#, so you don’t need to do type conversion.
  • 22.
    .NET Core Customizing theTag Helper element font Views – Tag Helpers
  • 23.
    .NET Core Authoring TagHelpers Views – Tag Helpers A tag helper is any class that implements the ITagHelper interface. However, when you author a tag helper, you generally derive from TagHelper, doing so gives you access to the Process method. Create a folder to hold the Tag Helpers called TagHelpers. The TagHelpers folder is not required, but it is a reasonable convention.
  • 24.
    .NET Core Authoring TagHelpers – Sample Email Helper Views – Tag Helpers <email>Support</email>  <a href="mailto:Support@contoso.com">Support@contoso.com</a>
  • 25.
    .NET Core Authoring TagHelpers – Sample Email Helper Views – Tag Helpers • The EmailTagHelper class derives from TagHelper. The TagHelper class provides methods and properties for writing Tag Helpers. • The overridden Process method controls what the tag helper does when executed. The TagHelper class also provides an asynchronous version (ProcessAsync) with the same parameters. • The context parameter to Process (and ProcessAsync) contains information associated with the execution of the current HTML tag. • The output parameter to Process (and ProcessAsync) contains a stateful HTML element representative of the original source used to generate an HTML tag and content.
  • 26.
    .NET Core Authoring TagHelpers – Sample Email Helper Views – Tag Helpers To make the EmailTagHelper class available to all our Razor views, we will add the addTagHelper directive to the Views/_ViewImports.cshtml file: @using AuthoringTagHelpers @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @addTagHelper "AuthoringTagHelpers.TagHelpers.EmailTagHelper, AuthoringTagHelpers“ <address> <strong>Support:</strong><email>Support</email><br /> <strong>Marketing:</strong><email>Marketing</email> </address>
  • 27.
    .NET Core Authoring TagHelpers – Sample Email Helper Views – Tag Helpers
  • 28.
    .NET Core Authoring TagHelpers – Sample Email Helper Views – Tag Helpers <address> <strong>Support:</strong><email mail-to="Support"></email><br /> <strong>Marketing:</strong><email mail-to="Marketing"></email> </address> Note: If you were to write the email tag self-closing (<email mail-to="Rick" />), the final output would also be self-closing. To enable the ability to write the tag with only a start tag (<email mail- to="Rick">) you must decorate the class with the following:
  • 29.
    .NET Core Authoring TagHelpers – Sample Email Helper Views – Tag Helpers With a self-closing email tag helper, the output would be <a href="mailto:Rick@contoso.com" />. Self-closing anchor tags are not valid HTML, so you wouldn’t want to create one, but you might want to create a tag helper that is self-closing. Tag helpers set the type of the TagMode property after reading a tag.
  • 30.
    .NET Core Authoring TagHelpers – Sample Email Helper Views – Tag Helpers An asynchronous email helper
  • 31.
    .NET Core Authoring TagHelpers – Sample Bold Helper Views – Tag Helpers [HtmlTargetElement("bold", Attributes = "bold")]
  • 32.
    .NET Core Authoring TagHelpers – Web site information Helper Views – Tag Helpers
  • 33.
    .NET Core Authoring Tag Helpers– Web site information Helper Views – Tag Helpers
  • 34.
    .NET Core Authoring Tag Helpers– Web site information Helper Views – Tag Helpers
  • 35.
    .NET Core Note Views –Tag Helpers Tag helpers translates Pascal-cased C# class names and properties for tag helpers into lower kebab case. Therefore, to use the WebsiteInformationTagHelper in Razor, you’ll write <website-information />. We are not explicitly identifying the target element with the [HtmlTargetElement] attribute, so the default of website-information will be targeted. If you applied the following attribute (note it’s not kebab case but matches the class name): [HtmlTargetElement("WebsiteInformation")]
  • 36.
    .NET Core Note Views –Tag Helpers The lower kebab case tag <website-information /> would not match. If you want use the [HtmlTargetElement] attribute, you would use kebab case as shown below: [HtmlTargetElement("Website-Information")]
  • 37.
    .NET Core Note Views –Tag Helpers The lower kebab case tag <website-information /> would not match. If you want use the [HtmlTargetElement] attribute, you would use kebab case as shown below: [HtmlTargetElement("Website-Information")]
  • 38.