How can I make a tag helper for images in .Net 5?

  • Page Owner: Not Set
  • Last Reviewed: 2022-01-06

I want to make a tag helper to auto add height and width. How do I?


Answer

View Imports:

@addTagHelper GateCityBank.Web.Business.Helpers.*, GateCityBank.Web

HI JUST A NOTE: The arguments for addTagHelper are namespace, then assembly. Thanks have a great day.

View:

<Image src="@Model.Page.PageImage" />

Some .cs file:

[HtmlTargetElement("Image", Attributes = "src")]
public class ImageHelpers : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "img";
        output.TagMode = TagMode.SelfClosing;

        var sizes = context.AllAttributes["sizes"].Value as List<ImageSize>;

        if (int.TryParse(context.AllAttributes["src"].Value.ToString(), out var imgId))
        {
            var imgRef = new ContentReference(imgId);
            var image = imgRef.Get<ImageFile>();

            var imgUrl = new UrlBuilder(imgRef.GetFriendlyUrl());
          
            output.Attributes.SetAttribute("src", imgUrl);
            output.Attributes.SetAttribute("alt", imgRef.GetAltText());
            output.Attributes.SetAttribute("width", image.Width);
            output.Attributes.SetAttribute("height", image.Height);
        }
    }