Home » Blog » .NET 6 MVC Series – Article 7 – Tag Helpers

.NET 6 MVC Series – Article 7 – Tag Helpers

article 7-tag helpers

In this article, we will learn about:

  • Tag Helpers
  • Create a custom tag helper

What are Tag Helpers

  • From the point of view of a layman – a tag helper is a server-side component that helps to generate a useful piece of HTML to be used on the views.
  • .NET provides a bunch of tag helpers, and we have used them in our earlier articles.
  • We have used the input & select tag helper extensively in our forms.
<div class="form-group">
        <label for="city">City</label>
        <input type="text" class="form-control" asp-for="City">
        <span asp-validation-for="City" class="text-danger font-weight-bold"></span>
</div>

Difference between a Tag Helper and an HTML Helper

  • One thing that I like about Tag Helpers is its simplicity and resemblance with native HTML elements.
  • HTML helpers more or less are invoked as methods that are mixed with HTML inside the razor views.

Syntax difference:

    <div class="form-group">
        <label for="city">City with Tag Helper</label>
        <input type="text" class="form-control" asp-for="City">
        <span asp-validation-for="City" class="text-danger font-weight-bold"></span>
    </div>

    <div class="form-group">
        <label for="city">City with HTML Helper</label>
        @Html.TextBoxFor(m=>m.City,new {@class="form-control"})
        @Html.ValidationMessageFor(m=>m.City, message:"City can't be empty",new {@class="text-danger font-weight-bold"})
    </div>

Tag Helpers provide a more native HTML kind of feel while creating/designing forms and web pages, as compared to the HTML Helpers.

Create a Custom Tag Helper

.NET provides an abstract class TagHelper which we can inherit and create a custom tag helper.

TagHelper abstract class
  • We will create a ProfileImageTagHelper to be used on web pages and forms.
  • Let’s create a class as ProfileImageTagHelper and inherit it with TagHelper abstract class.
  • We will override the Process() method of the abstract class.
[HtmlTargetElement(tag: "profile-image")]
    public class ProfileImageTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
        }
    }
  • The HtmlTargetElement represents via which tag the custom tag helper needs to be referred.
  • Let’s now add certain properties whose values need to be dynamic.
[HtmlTargetElement(tag: "profile-image")]
    public class ProfileImageTagHelper : TagHelper
    {
        public string ImageSrc { get; set; }
        public int ImageWidth { get; set; }
        public string ImageHeight { get; set; }
        public string Tooltip { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "img";
            output.TagMode = TagMode.SelfClosing;
            output.Attributes.Add("src", ImageSrc);
            output.Attributes.Add("height", ImageHeight);
            output.Attributes.Add("width", ImageWidth);
            output.Attributes.Add("style", "border-radius:50%");
            output.Attributes.Add("title", Tooltip);
        }
    }

We have added ImageSrc, ImageWidth, ImageHeight, and Tooltip properties to the class. These properties get added to the TagHelperOutput attributes.

The HTML element which is targeted over here is the img element.

In order to use a custom tag helper, we need to add it in the _ViewImports.cshtml file.

@using FirstMVCProject
@using FirstMVCProject.Models
@using FirstMVCProject.Enums
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@*Add custom tag helper below*@
@addTagHelper *,FirstMVCProject

Use the custom tag helper in the views

Let’s now use the ProfileImageTagHelper in the views.

    <profile-image image-src="/images/cute-cat.jpg" 
    image-height="100" image-width="100" tooltip="This is a cute cat" />
cute cat

Let’s add another one:

<profile-image image-src="https://picsum.photos/id/237/200/300" image-height="200" 
image-width="200" tooltip="This is cute dog"/>
cute dog

A full IntelliSense support is provided with the custom tag helper, which is quite good and helps in ease of development.

Github Link

The updated code is available here.

Conclusion

We have studied Tag Helpers in .NET 6 MVC and have learned how to create and use a custom tag helper.

Stay tuned for the next article.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *