Search code examples
asp.net-coretag-helpersasp.net-core-tag-helpers

How do I allow my ASP.NET Core tag helpers to be self-closing


I have written a tag helper that I can use as follows...

<mytaghelper attr1="jim"></mytaghelper>

I would like to be able to shorten this to just...

<mytaghelper attr1="jim">

...or at least...

<mytaghelper attr1="jim"/>

However, I can't get this to work. Here is some sample code for the Process method...

public override void Process(TagHelperContext context, TagHelperOutput output) {
  output.TagName = "div";
  output.PreContent.SetHtmlContent("<div>");
  output.Content.SetHtmlContent("OUTPUT HTML GOES HERE");
  output.PostContent.SetHtmlContent("</div>");
  output.Attributes.Clear();
}

I have tried adding a TagStructure setting to the HtmlTargetElement attribute on the class...

[HtmlTargetElement("mytaghelper", TagStructure = TagStructure.WithoutEndTag)]

...but it doesn't seem to make any difference. <mytaghelper attr1="jim"/> generates <div /> and <mytaghelper attr1="jim"></mytaghelper> generates <div></mytaghelper>.

If I set the TagStructure to NormalOrSelfClosing then included a closing tag works, but <mytaghelper attr1="jim"/> gives an empty <div />

Anyone able to explain what I need to do?


Solution

  • TagStructure.WithoutEndTag is able to write the tag with only a start tag or self-closing, but the output would be <div > or <div/> . Self-closing anchor tags are not valid HTML, so you wouldn't want to create one, but you might want to create a tag helper that's self-closing. Tag helpers set the type of the TagMode property after reading a tag. Add the below code line Inside the process method:

    output.TagMode = TagMode.StartTagAndEndTag;
    

    Take a moment to read Author Tag Helpers in ASP.NET Core which covers this perfectly .