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?
The opt-out character (“!”) is used to disable the Tag Helper at the element level. With the opt-out character, the HTML will not be generated for the label tag in the above case. We can use this opt-out character if we want to conditionally control rendering of the HTML elements.
To create custom tag helper, the first step is to create a class that inherits from "TagHelper" class. This class has a virtual method to generate HTML tags. It contains both synchronous (Process) and asynchronous (ProcessAsync) implementation of the virtual method.
The EmailTagHelper class derives from TagHelper . The TagHelper class provides methods and properties for writing Tag Helpers. The overridden Process method controls what the tag helper does when executed. The TagHelper class also provides an asynchronous version ( ProcessAsync ) with the same parameters.
Tag Helpers are attached to HTML elements inside your Razor views and can help you write markup that is both cleaner and easier to read than the traditional HTML Helpers. HTML Helpers, on the other hand, are invoked as methods that are mixed with HTML inside your Razor views.
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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With