Tag helpers are a brand new feature in ASP.NET Core that greatly enhances front-end development by keeping the developers "in the HTML". This tutorial covers the built-in tag helpers as well as creating custom tag helpers.
- [Instructor] Tag helpers are a brand new feature in ASP.NET Core. They enable server-side code to participate in rendering HTML elements in Razor views, and they definitely reduce the transition between code and markup. Instead of having to understand how the HTML helpers work, designers don't really understand creating anonymous objects and using those for CSS class names or other HTML attributes. They really just want to write HTML.
They're fully supported with IntelliSense, and they are used by attaching to HTML elements in views. You could also create custom tag helpers to cut down on repeated code. Let's start with the form tag helper, probably the most involved, and there are several tags. All of the tags in ASP.NET Core tag helpers start with asp- so you just start with a normal form tag in HTML and then you can add the area, the controller, the action.
You can optionally add in asp-antiforgery. It's true by default, but you could turn it off if you have a reason to, but I'm not sure what that reason would be. You can also add in all of the route parameters by doing asp-route-parametername. For example, asp-route-id=1. You can also use a dictionary if you want, although that does add some friction back into it, and you can use asp-route for named routes which obviously would supersede using the controller and action tags.
You can find the equivalent functionality in the HTML.BeginForm and EndForm helpers. Keeping in the theme of forms, there are form field tag helpers as well which include the input, TextArea and select tag helpers. You have full access to the model properties with the asp-for, and they automatically generate the ID and name values based on the model property. If you have validations on your model, then the tag helpers will also add in the HTML validation attributes.
Looking at each of these specifically, the input form field tag helper adds the HTML type based on the .NET data type. For example, boolean turns into a checkbox, EmailAdress type equals email, and it's equivalent to the HTML.TextBoxFor or HTML.EditorFor helpers. There's a TextArea tag helper, also uses asp-for and it's equivalent to the HTML.TextAreaFor helper.
And the select tag helper takes two tags, the asp-for but also the asp-items, which then become the options in the select box. The label tag helper will decorate the for attribute in HTML by using the asp-for the model property. It is equivalent to the HTML.LabelFor helper. In the final form tag helper or the validation tag helpers, we get the validation message, which is for a specific property using the asp-validation-for tag, and it generates the data-valmsg-for attribute.
The validation summary uses the asp-validation-summary tag and is equivalent to the HTML.ValidationSummary helper. Let's look at these in code. Here in the login view, we have a form tag helper and it's got the controller and action specified, and those are both here on line 15. Then, we have a route parameter, which is asp-route-parameter name, or returnurl, and then you have regular HTML attributes for the method and the CSS class.
Next on line 20, we have a validation summary. You can select different options. This'll show all validation errors. If we use IntelliSense, we can also do model only or none which essentially turns off the validation summary. The label tag helper on line 22, asp-for, that's the email model property. That will then create the label for the input tag helper on line 24.
This is an input asp-for equals Email and we'll render the HTML type equals mail. The following line, 25, shows the validation-for, and again, you specify the model property. This'll show up if there are any client-side validation errors or server-side validation errors if client-side is turned off. There are also some non-form related tag helpers, anchor, environment, link, script and image, and then cache and distributed cache.
The anchor tag helper builds a link, and just like the form, it supports the area, controller and action, as well as route and route parameter tags. You can also set the protocol for HTTP or HTTPS. You can add a fragment, and a hostname. The environment tag helper conditionally renders content based on the runtime environment. I had mentioned this when we were talking about the environmental awareness, and this is one of the every powerful ways that that awareness is used.
This has changed a little bit in 2.0, just a syntax, where the include and exclude attributes are added, and we'll cover that in detail in the 2.0 section. The link tag helper has an asp-appended-version tag, and what this does is it adds a hash of the file to the URL. If the file changes but the name doesn't, the URL is recognized as being different and the browser will automatically reload that file without having to play the name change game.
There's also a lot of href handling tags with this, so you can include and exclude, which you provide a globbed list of files to either include or exclude. Then, if you are using a content delivery system, there's a fallback-test class property and value, and that's where they're going to test the original source, the property used for the test, and the value that should be returned. If the test fails, then you can use the asp-fallback.href and the href include exclude to provide fallback information if the primary file fails to load.
The script tag helper is very similar. It also has the asp-append-version tag, and it has the src-include and exclude so you can have multiple files with one tag. There's a fallback-test, and that is a script method to execute to see if the source was actually loaded. Then, there's a fallback-src of where to fallback to if the primary file fails to load, and just like the link tag helper, you've got the include and exclude options on the fallback.
The image tag helper provides the asp-append-version tag which, just like the other two we just discussed, it resolves issues with files being cached because it creates a hash of that file and appends that to the URL. The cache tag helper provides a way to mark content as cached using the cache tag. It supports absolute, timespan, or sliding expiration, and it also supports various cache options such as all of the variables.
The distributed cache helper inherits from the cache tag helper, but additionally supports SQL Server or Redis as a distributed cache. Let's look at these in code. If we go to the top of the layout file, we here see the environment tag helper, and if we are in development, it loads up the full version of Bootstrap and site.css. If we are in the staging or production, it will then load from a CDN the minified version, at least for Bootstrap, but the local minified version for the site.css, and also provides for the Bootstrap file where it should get the CSS if it needs to fall back, but also how to test, so it's going to look for the class sr-only, it's going to test a property position, and if it finds a value absolute, it knows the file from the CDN successfully loaded.
Here are some examples of the link tag helper. We have a regular hyperlink that's sitting in the area, controller, action, and a class. We can also add in route parameters, and we can find an example of that in our view component menu where we actually have a link that has the controller action and then the route ID.
Here are some script tag helpers surrounded by environment tag helpers. Here on line 58 is trying to get the jQuery minified off of a CDN if we are in staging or production, and it provides the fallback source and the fallback test. Now that you've seen the builtin tag helpers, you can also build custom tag helpers. User built C+ classes that derive from Tag Helper, and any public properties exposed by your class become lower-kebab-cased attributes on the tag.
There's one method you need to worry about, and that's a process method, and that builds the rendered tag. To use these, you have to register the assembly containing the custom tags in the ViewImports.cshtml. If you look at the email tag helper that I've built, I have two public properties on lines 13 and 14, EmailName and EmailDomain, and then the process method, let me line this up so it's easier to read, it determines that the tag name will be an A, builds the address from the properties and then sets the href attribute with the mailto value and then sets the content.
We then register these in ViewImports.cshtml, and we do that right here with the addTagHelper. The asterisk means we want all of the tags included and then the name of the assembly. Finally, to use these, we can open up the Contact.cshtml view, and you see them being used here. Let me make this spacing a little easier to see with this font. So, we have the name of the tag helper class minus the actual tag helper suffix, and then the parameters or the properties become lower-kebab cased.
Very simply, you can create a class that will eliminate repetitive typing in your HTML.
- Running and debugging ASP.NET Core applications
- Pros and cons of migrating existing applications to ASP.NET Core.
- Built-in dependency injection
- Environment awareness and app configuration
- Web host configuration and SSL
- View components invoked as tag helpers
- Configuration and logging
- Using Razor Pages