Tag Helpers are new features in ASP.NET Core, which help us add the server side code easily into our HTML markup. In this tutorial, we will make use of them to update the HTML form, which we created in the previous tutorial on strongly typed view.
Table of Contents
What is a Tag Helper
The Tag helpers help us to write HTML elements in easy-to-use razor syntax. They look just like standard HTML code but it is processed by Razor engine on the server giving it all the advantageous of server-side rendering.
The razor markup created using the Tag Helpers looks like standard HTML elements. They manipulate the HTML elements on which they are operated or insert new HTML elements, or replace the existing content with the new one.
For Example, by using the Form Tag Helper, we can rewrite the <form> tag as shown below. Here the asp-action & asp-controller are attributes of the Form Tag Helper.
1 2 3 | <form asp-action="create" asp-controller="home"> |
And it translates into
1 2 3 | <form action="/home/create" method="post"> |
Purpose of Tag Helpers
You can create forms without using the Tag Helpers ( or HTML Helpers) as we shown in the Forms in ASP.NET Core.
But, the Tag Helpers simplify the code required to generate the view’s HTML output based on the data provided to it. For Example Label Tag Helper generates the caption based on the display Data Annotation attribute. Similarly, the Input Tag Helper renders id, name & type HTML attribute based on the Model data type & Data Annotation attribute.
How to use Tag Helpers
The ASP.NET Core MVC Tag Helpers resides in the assembly Microsoft.AspNetCore.Mvc.TagHelpers assembly. We need to import it to use the Tag Helpers
Adding the Tag Helpers using @addTagHelper
To use the Tag Helpers, you need to add a @addTagHelper directive to view, or in specific views where you want to use them.
1 2 3 | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers |
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 the view
Making the Tag Helpers available globally
Adding the @addTagHelper to specific view makes it available only to that view.
You can add the @addTagHelper directive to the _ViewImports.cshtml, which makes it to available in all the views.
Removing the Tag Helpers
The @removeTagHelper is used to remove them from a specific view. The syntax of the @removeTagHelper is similar to the @addTagHelper
1 2 3 | @removeTagHelper ScriptTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers |
The above @removeTagHelper directive removes the ScriptTagHelper from the View.
Removing all the Tag Helpers
The code below removes all the tag helpers from the assembly Microsoft.AspNetCore.Mvc.TagHelpers from the specific view.
1 2 3 | @removeTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" |
Selectively Adding the Tag Helpers
Instead of adding all helpers, you can selectively add the helper you need.
1 2 3 | @addTagHelper "Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers" |
! Tag Helper opt-out character
By prefixing the ! before an HTML element, you will be able to disable the tag helper for that element.
1 2 3 | <!label asp-for="Name"></!label> |
The label Tag helper is disabled for the above code
You must apply the Tag Helper opt-out character to the opening and closing tag.
Using @tagHelperPrefix to selectively opt-in.
Instead of selectively opting out using the opt-out character !, you can use the @tagHelperPrefix to selectively opt-in for tag helper
To do that you must first define the opt-in prefix using the @tagHelperPrefix as shown below.
1 2 3 | @tagHelperPrefix th: |
Now, the th: must be prefixed to every tag helper in the view, so as to enable tag helper on them
1 2 3 4 5 | <th:label asp-for="Name"></th:label>Â Â //Tag helper is enabled <label asp-for="Address"></label>Â Â Â Â Â //Tag helper is disabled |
Example of Tag Helpers
We built a simple Form in the previous tutorial. Let us add the Tag Helpers to that form.
First, Open the HomeController.cs and change Create Action method as follows.
1 2 3 4 5 6 7 8 | [HttpGet] public IActionResult Create() { ProductEditModel model = new ProductEditModel(); return View(model); } |
The Instance of the ProductEditModel is passed to the View creating a Strongly Typed View.
Open the Create.cshtml from the folder /Views/Home.
Form Tag Helper
The Form Tag Helper is bound to the HTML <form> element.
The Form Tag Helper provides several server-side attributes which help us to manipulate the generated HTML. Some of the available attributes are
asp-controller: The name of the MVC controller to use
asp-action: The name of the MVC Controller action method to use
asp-area: The name of the Controller Area to use
For example
1 2 3 | <form asp-controller="Home" asp-action="Create"> |
The above code translated into
1 2 3 4 5 | <form method="post" action="/Home/Create"> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8PlIso5McDBOjgPkVg9O4mnNiAE8U0HkVlA9e-Mtc76u7fSjCnoy909Co49eGlbyJxpp-nYphF_XkOrPo0tTGdygc2H8nCtZCcGURMZ9Uf01fPOg5jRARxTHXnb8N6yYADtdQSnJItXtYsir8GCWqZM" /> </form> |
Note that the Form tag helper has automatically inserted an Anti-forgery token into the generated HTML.Â
Label tag Helper
The LabelTagHelper is applied to the label HTML elements. It has one server-side attribute named asp-for. It is used as shown below
1 2 3 | <label asp-for="@Model.Name"></label> |
Which translates into
1 2 3 | <label for="Name">Name</label> |
The caption name is picked up from the model property name or from the data annotations applied on the model property.
Using @Model keyword is optional here. You can directly use the model property name as shown below.
1 2 3 | <label asp-for="Name"></label> |
You can read how to pass the model to view from the tutorial Strongly typed view
You can read more about Label Tag Helper
Input Tag Helper
Similarly, the Input tag Helper is applied to the input HTML element.
1 2 3 | <input asp-for="Name" /> |
Which translates into
1 2 3 | <input type="text" id="Name" name="Name" value="" /> |
The type, id & name attributes are automatically derived from the model property type & data annotations applied on the model property
Finally, our HTML form will look like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <form asp-controller="Home" asp-action="Create"> <label asp-for="Name"></label> <input asp-for="Name" /> <label asp-for="Rate"></label> <input asp-for="Rate" /> <label asp-for="Rating"></label> <input asp-for="Rating" /> <input type="submit" name="submit" /> </form> |
The Above form translates into
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <h2>Create</h2> <form action="/Home/Create" method="post"> <label for="Name">Name</label> <input type="text" id="Name" name="Name" value="" /> <label for="Rate">Rate</label> <input type="text" data-val="true" data-val-number="The field Rate must be a number." data-val-required="The Rate field is required." id="Rate" name="Rate" value="0.00" /> <label for="Rating">Rating</label> <input type="number" data-val="true" data-val-required="The Rating field is required." id="Rating" name="Rating" value="0" /> <input type="submit" name="submit" /> <input name="__RequestVerificationToken" type="hidden" value="CfDJ8PlIso5McDBOjgPkVg9O4mlYQIZDgGzfiyx_ZiUck9A5E6DqBMIPnDCjFTyw5As2ALJT34MG_lmaAanTwCeq1ugZ1r7w7qBsQCIgmO7Zw1C6CFvJNj6y4kxrSq0PT0Lk7XXqPv9NDsTL7C-6aB85Mjo" /> </form> |
You can read more about input tag helper
Advantages of Tag Helpers
The Tag helpers offer several benefits
An HTML-friendly development experience
The Tag Helpers look like standard HTML elements. The Front-end Developers need not learn the C# or razor syntax to add these elements in the view. and thus more easily achieving the separation which concerns.
You can easily add CSS element or any HTML attribute to tag helpers just like an HTML element
A Rich IntelliSense Help
The Tag Helpers provide a Rich IntelliSense help
The following image shows the intellisense help as you type <label asp-for=”Rating”></label>
Cleaner Code
The Code becomes cleaner & more readable compared to using the HTML Helpers. There is no need to use the @ escape sequence to shift between C# code and HTML Markup.
Extensible
ASP.NET Core MVC provides many built-in Tag Helpers to help us to create the view. But if these Helpers do not suit your needs, then you can create your own Tag Helper. You can also extend the existing Tag Helpers also.
We will show you how to create your own Tag Helpers in one of the future articles
List of Built-in Tag Helpers
The Microsoft.AspNetCore.Mvc.TagHelpers assembly consists of many built-in Tag Helpers for common tasks such as creating forms, validation summaries, labels, links etc.
TagHelper | Targets | Attributes |
---|---|---|
Form Tag Helper | <Form> | asp-action, asp-all-route-data, asp-area, asp-controller, asp-fragment, asp-host, asp-page, asp-page-handler,asp-protocol,asp-route, asp-route- |
Anchor Tag Helpers | <a> | asp-action, asp-all-route-data, asp-area, asp-controller, asp-Fragment, asp-host, asp-page, asp-page-handler, asp-Protocol, asp-route, asp-route- |
Cache Tag Helper | <cache> | enabled1,expires-after2,expires-on3,expires-sliding4,priority5,vary-by6 |
Environment Tag Helper | <environment> | names, include, exclude |
Image Tag Helper | <img> | append-version |
Input Tag Helper | <input> | for |
Label Tag Helper | <label> | for |
Link Tag Helper | <link> | href-include, href-exclude, fallback-href, fallback-href-include, fallback-href-exclude, fallback-test-class, fallback-test-value, fallback-test-property, fallback-test-value, append-version |
Options Tag Helper | <select> | asp-for, asp-items |
Partial Tag Helper | <partial> | name,model,for,view-data |
Script Tag Helper | <script> | src-include, src-exclude, fallback-src, fallback-src-include, fallback-src-exclude fallback-test, append-version |
Select Tag Helper | <select> | for, items |
Textarea Tag Helper | <textarea> | for |
Validation Message Tag Helper | <span> | validation-for |
Validation Summary Tag Helper | <div> | validation-summary |
Summary
In this tutorial, we learnt what is Tag Helpers are and how to make use of them, while building HTML Forms. The Tag Helpers are the powerful new feature added in the ASP.NET Core. In the next few tutorials, we will look at some of the important Tag Helpers in detail