So I am working with custom tag helpers and i ran into a (possible) problem. I have JSON files containing some embedded HTML mark up (img, links) mostly. I have written a custom Image Tag Helper to alter the attributes. However I noticed that html rendered through Html.Raw() will not invoke the tag helper.
Question: Is it possible to add an extension method to Html.Raw(), if so how?
Or am i doing something wrong with my tag helpers and the image tag helper should in fact be invoked by the rendered elements?
Also the tag helper does work for standard rendered images.
some code
viewimports
@using projectname.de
@using projectname.de.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, projectname.de
Tag helper
[HtmlTargetElement("img", TagStructure = TagStructure.WithoutEndTag)]
public class ImageTagHelperExtension : TagHelper
{
public string? Src { get; set; }
public string? Alt { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (!string.IsNullOrEmpty(Src))
{
output.Attributes.Add("src", $"https://www.sitenames.com/{Src.ToLower()}");
}
if (string.IsNullOrEmpty(Alt))
{
output.Attributes.Add("alt", "image alt tag");
}
}
}
Html.Raw()in ASP.NET Core does not process custom tag helpers.You can preprocess the HTML content on the server before sending it to the view by using
HtmlAgilityPack.Install HtmlAgilityPack
Create a static method to process HTML
Use the method in your razor view
Backend code