Showing posts with label Tag Helpers. Show all posts
Showing posts with label Tag Helpers. Show all posts

Wednesday, April 11, 2018

All about Tag Helpers in ASP.NET Core 2.0

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:

@addTagHelper *,Microsoft.AspNetCore.Mvc.TagHelpers            
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:
  1. public class AppreciateTagHelper:TagHelper  
  2. {  
  3.         private const string appreciationText = "Great work";  
  4.         public string PersonName { getset; }  
  5.         public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)  
  6.         {  
  7.             output.TagName = "Appreciation";  
  8.             string message = $"{appreciationText}, {PersonName}";   
  9.             var attribute = new TagHelperAttribute(name: "Label", value: message);  
  10.             output.Attributes.Add(attribute);  
  11.             output.Content.SetContent(message);  
  12.         }      
  13. }                  
Next is to import the newly created Tag Helper and that can be done by adding a line in _ViewImports.cshtml file as shown below:
  1. @addTagHelper *,CustomTagHelper  
Then last is to update the respective view and the code for that is:
  1. <appreciate person-name="Shweta"></appreciate>      
We are all set with our custom Tag Helper and now it's time to view it in a browser. Quickly run the application and verify the output. You would be able to see the output as shown below:


1) One has the benefit of getting away from the @ symbol in RAzor view and code looks cleaner, maintainable and readable.
2) Tag Helpers are not a replacement of HTML helpers.
Hope you enjoyed knowing about Tag Helpers.

Friday, February 5, 2016

Tag Helpers in ASP.NET Core 1.0

Exclusive Amazon Deals
This article is for those who would like to use Tag Helpers over old Razor/HTML helpers. Tag Helpers, another new feature of ASP.NET Core. Let’s quickly have a look at it.

What are Tag Helpers?
As per ASP.NET documentation:
                    "Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files".

Tag Helpers are somewhat similar to HTML Helpers/Razor Helpers introduced in previous version of ASP.NET MVC but those helpers were not that easy to understand for web designers because of inline C# method calls. As web designers are more inclined towards HTML, a simpler and comfortable approach was required. Fortunately, ASP.NET Core 1.0 provided that. Now one need not to use HTML Helpers to build cshtml forms. Means when you had to write this:

Now you can write this:

As you can see above format is very easy to understand as it is purely a HTML syntax.

How Tag Helpers work?

When you create a new ASP.NET web application in Visual Studio, it adds Microsoft.AspNet.Tooling.Razor to the project.json file. This is the package that adds Tag Helper tooling and enables intelliSense in Visual Studio. In order to make our Razor views aware of Tag Helpers, a special file named _ViewImports.cshtml is used. This file is stored in Views folder. By default this file will be there. By any chance if file is not there, then create it and add following line in it:

Pre-defined Tag Helpers

ASP.NET Core 1.0 includes a list of pre-defined Tag Helpers:

Anchor - generates hyperlink
Input - generates input elements
Select – generates dropdownlist
Cache – manages partial page caching
Form – generates form element
Script – processes script tag
Link – processes link element
Label – outputs label element
Option – targets individual options in a list                   
TextArea – processes textarea tag
Environment – controls rendering of content
ValidationMessage – generates validation error
ValidationSummary – provides validation summary message
I’ll try to brief about all above Tag Helpers in coming posts. Now what if existing tags doesn't fulfill our need? In that case, we have to go ahead and invent something else. Should we proceed to create Tag Helper based on our requirement? 
Creating Custom Tag Helpers
As part of this article, we will create a new Tag Helper for appreciating someone. Our tag will be <appreciate>. For example:
<appreciate person-name-for-appreciation="shweta"></appreciate>
The server will use appreciate Tag Helper to convert that markup into following:
<label>Great Work, Shweta</label>
In order to create this new Tag Helper, we have to create a new class named AppreciateTagHelper and inherit TagHelper in that. Make sure to add the reference of Microsoft.AspNet.Razor.TagHelpers in this new class. Sample code is as:

Note - it is not mandatory to suffix TagHelper in class name. It is just a good practice.
To make this Tag Helper available to all Razor views, we have to add addTagHelper directive to _ViewImports.cshtml file as:
@addTagHelper "*,CustomTagHelper"
Above statement signifies that all the custom Tag Helpers (denoted by wild card character) will be available from assembly named CustomTagHelper. If interested, instead of * you can go with fully qualified names also.
Next step is to update our views. Let’s go ahead and append below line in view:
<appreciate person-name-for-appreciation="shweta"></appreciate>
Good thing is, you will get intelliSense for your custom Tag Helper also J
Run your application and you will find that appreciate Tag Helper is replaced with your label markup with output as:

Hope you enjoyed learning this new feature.