Search code examples
asp.net-coreasp.net-core-mvcasp.net-core-2.0tag-helpersasp.net-core-tag-helpers

ASP.Net Core: Output 2 tags from one tag helper


Using ASP.Net Core's Tag Helpers, is there any way to convert 1 tag into 2 tags at the root level? I know you can remove a tag completely using TagHelperOutput.TagName == null, but I'm wondering how I can do the opposite to output more than one tag.

For example, go from:

<canonical href="/testing" />

to:

<link rel="canonical" href="http://www.examples.com/widgets" />
<link rel="next" href="http://www.examples.com/widgets?page=2" />

Here is an example tag helper that outputs one of the tags, but not both:

[HtmlTargetElement("canonical")]
public class CanonicalLinkTagHelper : TagHelper
{
    public string Href { get; set; }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "link";
        output.Attributes.SetAttribute("rel", "canonical");
        output.Attributes.SetAttribute(new TagHelperAttribute("href", new HtmlString(Href)));
    }
}

Solution

  • According to this documentation, once you have used TagHelperOutput.TagName == null to remove your tags, you must be able to add custom HTML using output.PostContent.AppendHtml()

    Update

    PostContent is only to append after. To replace entire content you will need to use output.Content.SetHtmlContent(