Back to all posts

Turbocharge Developer Productivity with Bootstrap Tag Helpers

Posted on Apr 12, 2022

Posted in category:

I strive to be as efficient and consistent as possible with all things development. I recently took some time to look at common development patterns that I was utilizing across multiple projects and created several tag helpers to help optimize the development experience. The TagHelpers we will explore in this post are focused primarily on development using Bootstrap for UI elements.

What I Didn't Like

In reviewing projects that we were working on, I found that we consistently used large blocks of duplicated/repeated code. One example would be the following used to collect a users' email address.

Existing Code
<div class="form-group">
    <label asp-for="EmailAddress" class="control-label"></label>
    <input asp-for="EmailAddress" class="form-control" />
    <span asp-validation-for="EmailAddress" class="text-danger"></span>
    <span class="form-text text-muted">Email that should receive notification.</span>

Nothing out of the ordinary here, and something that I've taken as a "cost of doing business in the past years, and auto-complete help make it "less tedious."

Tag Helper Improvements

Dissecting the above, it is clear that we are simply wrapping 3 or 4 different tag helper calls inside a single outer div. I dug into the inner workings of the ASP.NET Core tag helpers and realized that they use the IHtmlGenerator object to generate the content under the hood. Given this information, I discovered that by extending the complex input tag helper, one could simply call IHtmlGenerator for the other elements with ease. This resulted in the above being shorted to.

<form-input asp-for="EmailAddress">
    <form-note>Email that should receive notification.</form-note>

This is a much-streamlined process, and comparing characters/lines, we see a 50% reduction in lines of code and a 66% reduction in characters.

Currently Supported Helpers

Currently, I have support for input, select, and text-area and other common bootstrap patterns such as modal dialogs and cards. I plan to add more, including support for bootstrap 5 and the current bootstrap 4 support. The Github Repository includes a sample project that shows usage of all helpers.

I welcome contributions and feedback both here and on the actual GitHub repository. I hope you find this as helpful as I do!