Reza Shirazi
Reza Shirazi

Reputation: 381

Asp.net MVC core custom tag helper not generate output

I implemented a custom tag helper to generate page numbers as a link. The "Process" method is triggered and the string builder has all the HTML content in it but it does not output the result on the screen. It just renders , Could anyone help, please?

<paginate page="Model.PageInfo" />



[HtmlTargetElement("paginate",
     TagStructure = TagStructure.WithoutEndTag)]
    public class PaginateTagHelper : TagHelper
    {
        public PageInfo Page { get; set; }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            StringBuilder html = new StringBuilder();
            html.Append("<div>");
            for (int i = 1; i <= Page.TotalPages; i++)
            {
                var tag = new Microsoft.AspNetCore.Mvc.Rendering.TagBuilder("a");
                tag.MergeAttribute("href", Page.PageUrl(i));
                tag.InnerHtml.AppendHtml(i.ToString());
                if (i == Page.CurrentPage)
                {
                    tag.AddCssClass("selected");
                    tag.AddCssClass("btn-primary");
                }
                tag.AddCssClass("btn btn-default");
                html.Append(GetTagContent(tag));
            }
            html.Append("</div>");
            output.Content.SetHtmlContent(html.ToString());
        }
        private string GetTagContent(IHtmlContent content)
        {
            using (var writer = new System.IO.StringWriter())
            {
                content.WriteTo(writer, System.Text.Encodings.Web.HtmlEncoder.Default);
                return writer.ToString();
            }
        }
    }

Upvotes: 1

Views: 894

Answers (1)

LazZiya
LazZiya

Reputation: 5729

Remove TagStructure = TagStructure.WithoutEndTag, self closing tags are not suitable for tags with inner content.

Self-closing TagHelpers

Many Tag Helpers can't be used as self-closing tags. Some Tag Helpers are designed to be self-closing tags. Using a Tag Helper that was not designed to be self-closing suppresses the rendered output. Self-closing a Tag Helper results in a self-closing tag in the rendered output.

Upvotes: 3

Related Questions