Lessons in this course (9)

5. ASP.NET Core: custom tag helpers

Intermediate★ Must knowLesson 5 of 9

Tag helpers let server code participate in rendering HTML-looking elements and attributes — editor-friendly and readable.

csharp
// <money amount="Model.Total" culture="en-IN"></money>  →  <span class="money">₹4,500.00</span>
[HtmlTargetElement("money")]
public sealed class MoneyTagHelper : TagHelper
{
    public decimal Amount { get; set; }
    public string Culture { get; set; } = "en-IN";

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "span";
        output.TagMode = TagMode.StartTagAndEndTag;
        output.Attributes.SetAttribute("class", Amount < 0 ? "money negative" : "money");
        output.Content.SetContent(Amount.ToString("C", CultureInfo.GetCultureInfo(Culture)));   // SetContent HTML-encodes
    }
}

// Attribute tag helper: <button asp-confirm="Delete this order?">Delete</button>
[HtmlTargetElement(Attributes = "asp-confirm")]
public sealed class ConfirmTagHelper : TagHelper
{
    [HtmlAttributeName("asp-confirm")] public string Message { get; set; } = "";
    public override void Process(TagHelperContext context, TagHelperOutput output)
        => output.Attributes.SetAttribute("onclick", $"return confirm('{JavaScriptEncoder.Default.Encode(Message)}');");
}
cshtml
@* Views/_ViewImports.cshtml *@
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Shop.Web

<money amount="Model.Total"></money>
<button type="submit" asp-confirm="Delete this order?">Delete</button>
HTML helper (@Html.TextBoxFor)Tag helper (<input asp-for>)
C# method call in markupHTML element/attribute
Harder for designers to readLooks like HTML, IntelliSense for attributes
Available in MVC 5 and CoreASP.NET Core only

Async tag helpers override ProcessAsync (e.g. to load data or get child content with output.GetChildContentAsync()).