Introducing TagHelpers in Asp Core

What is a TagHelper?

TagHelpers are the new way of writing server-side code that renders HTML tags(elements), that is much closer to HTML syntax than Razor.

Compared to Razor, the code is way cleaner, there is no context-switching, but for a newbie, might be very hard to understand at first.
Given the fact that there is no special syntax for the tags, and it might be hard to distinguish which attributes belong to HTML and which are for server-side rendering.

What I really enjoy about them is the fact that when you have multiple attributes to add, you have full IntelliSense support and the view code will look clean, and easy to understand.

Razor Syntax:

@Html.TextBoxFor(m=>m.FirstName, new { @class = "form-control", placeholder=”add a first name” })

TagHelper Syntax

<input asp-for="FirstName" placeholder=”add a first name” class="form-control" />.

Standard TagHelpers

Custom TagHelpers

For example, you have an app that works with superheroes(managing them etc.), and you work very often with the names of the superheroes, in different areas of the app, in MVC you would maybe:
– add a property in your model that is of type List<SelectListItem>, and pass it through
– use a ViewBag populated at controller action level that holds the key-value pairs for your dropdown
– or have a separate controller that serves you JSONs for your data and uses different repositories for different type of data
Either way, you might end up have something that works fine but it’s scattered around in different controllers, views,  making your code less clean.

@Html.DropDownListFor(model => model.FavoriteSuperHero, (List<SelectListItem>)ViewBag.SuperHeroNames, "Select One")

What happens if you project grows very much, or the team grows? How would you enforce some consistency across the team?
Well, TagHelpers saves you the trouble and let’s you write something once, and use it everywhere without an additional setup.

This is a very simple example, using a repository to bring some from the database and to populate a few HTML elements.

Server-side code:
[HtmlTargetElement("super-hero")]
    public class SuperHeroNamesTagHelper : TagHelper
    {
        public ISuperHeroesRepository _superHeroesRepository;

        public SuperHeroNamesTagHelper(ISuperHeroesRepository superHeroesRepository)
        {
            this._superHeroesRepository = superHeroesRepository;
        }

        public override void Process(TagHelperContext context,
            TagHelperOutput output)
        {
            output.TagName = "select";
            output.Attributes.SetAttribute("class", "awesome-select");

            var names = _superHeroesRepository.GetHeroNamesAndIds().ToList();
            foreach (var name in names)
            {
                var option = new TagBuilder("option")
                {
                    TagRenderMode = TagRenderMode.Normal
                };
                option.Attributes.Add("value", name.Id.ToString());
                option.InnerHtml.Append(name.Nickname);
                output.PostContent.SetHtmlContent(option);
                output.Content.AppendHtml(option);
            }

        }
}
View Code:

Of course, you are not

Leave a Comment

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