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

2

6

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?

Langan answered 14/5, 2019 at 13:40 Comment(0)
K
14

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 .

Kornher answered 24/5, 2019 at 6:41 Comment(1)
I have no idea what you mean about anchor tags, as I never mentioned them at all. However, the TagMode.StartTagAndEndTag did what I needed. Thanks for the link, it was very useful.Langan
T
1

The correct syntax is:

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

Which should be applied to the taghelper class, not the Process method. You may already be doing that, but it wasn't clear in your question. I believe you still must use the self-closing tag syntax (/>) for it work, though.

Tompkins answered 14/5, 2019 at 14:2 Comment(1)
Sorry, I wasn't clear enough. I did add the attribute to the class, and tried the option you showed, but it didn't work. Please see my updated question, where I (hopefully) clarified it, and showed what happens with both styles of tag. ThanksLangan

© 2022 - 2024 — McMap. All rights reserved.