Can I use a Tag Helper in a custom Tag Helper that returns html?

后端 未结 3 689
梦毁少年i
梦毁少年i 2020-12-30 23:39

I recently ran into a situation where I would like to use a tag helper within a tag helper. I looked around and couldn\'t find anyone else trying to do this, am I using a po

3条回答
  •  旧时难觅i
    2020-12-31 00:06

    If anyone's looking to reuse the built-in tag helpers from asp.net core, you can use the IHtmlGenerator instead. For reusing other types of tag helpers, I haven't found a simpler option then @N. Taylor Mullen answer

    Here is how to reuse the asp-action tag helper:

    [HtmlTargetElement("helplink")]
    public class RazorTagHelper : TagHelper
    {
        private readonly IHtmlGenerator _htmlGenerator;
    
        public RazorTagHelper(IHtmlGenerator htmlGenerator)
        {
            _htmlGenerator = htmlGenerator;
        }
    
        [ViewContext]
        public ViewContext ViewContext { set; get; }
    
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "div";
            output.TagMode = TagMode.StartTagAndEndTag;
            var actionAnchor = _htmlGenerator.GenerateActionLink(
                ViewContext,
                linkText: "Home",
                actionName: "Index",
                controllerName: null,
                fragment: null,
                hostname: null,
                htmlAttributes: null,
                protocol: null,
                routeValues: null
                );
            var builder = new HtmlContentBuilder();
            builder.AppendHtml("Here's the link: ");
            builder.AppendHtml(actionAnchor);
            output.Content.SetHtmlContent(builder);
        }
    }
    

提交回复
热议问题