This time rather than jumping directly into the topic, let's have a look at the Login form code which you must have definitely seen while working on MVC application.
What do you think about the above code snippet?
Indeed, it works alright, but there are few problems with this. But the major problem is its a bit messy and difficult to read due to excessive use of @. So, now we have understood the problem, what is the solution? Here comes the Tag Helpers for our rescue. Let's quickly have a look at the code generated by the ASP.NET Core framework for the same functionality:
The above code looks much cleaner. Isn’t it? If it looks interesting to you, we should learn more about it.
What are Tag Helpers
Tag Helpers are classes written in C# but are attached to HTML elements in order to run server-side code from Razor view. In other words, view created in HTML has its presentation logic defined in C#, which is ultimately executed on the web server. Examples of common built-in Tag Helpers are Anchor tag, Environment tag, Cache tag, etc. Understood...Not Understood...Confused?
No worries. As we will proceed further, things will be much clearer.
Using Tag Helpers
So, how do we go about using Tag Helpers? In order to use the inbuilt or custom Tag Helpers, one has to first reference Tag Helper library named Microsoft.AspNetCore.Mvc.TagHelpers. It can also be taken from Nuget. Once referenced, import it inside _ViewImports.cshtml using @AddTagHelper directive as shown below:
In the above line, all the Tag helpers will be imported which are mentioned in 'Microsoft.AspNetCore.Mvc.TagHelpers' assembly. As mentioned in my previous article, whatever is referenced/imported inside _ViewImports.cshtml will be available for all the views. If you don't want any of your views to use globally imported Tag Helpers, you can use @removeTagHelper in the respective view.
Where can I use Tag Helpers
Majority of Tag Helper use cases fall into one of these categories: 1) Take existing HTML elements and customize their output 2) Define totally new elements with custom or not output, i.e. Environment
Creating Custom Tag Helpers
Now we got a basic idea of what is Tag Helper, how about creating our own Tag Helper. Let's go ahead and quickly create our own Tag Helper step by step. I'll take a very simple scenario, in which we will introduce a simple tag named 'Appreciate' which will take the value as person name and same will be displayed on the screen with some nice appreciation.
Create a new class named AppreciateTagHelper and add the code as shown below: