TagBuilder InnerHtml in ASP.NET 5 MVC 6

后端 未结 6 968
难免孤独
难免孤独 2021-02-07 01:10

It seems to me that there are major breaking changes in TagBuilder as of beta7 with no mention about them in the announcements repo.

Specifically .ToString no longer ren

6条回答
  •  清酒与你
    2021-02-07 01:36

    Beta 8 solved this issue by adding an Append() method to tag helpers.

    For beta 7 the solution would be to use the BufferedHtmlContent() class, but since it is not accessible we must do some extra work.

    private class MyBufferedHtmlContent : IHtmlContent
    {
        internal List Entries { get; } = new List();
    
        public MyBufferedHtmlContent Append(IHtmlContent htmlContent)
        {
            Entries.Add(htmlContent);
            return this;
        }
    
        public void WriteTo(TextWriter writer, IHtmlEncoder encoder)
        {
            foreach (var entry in Entries)
            {
                entry.WriteTo(writer, encoder);
            }
        }
    }
    

    Usage:

    TagBuilder firstChild = new TagBuilder("input");
    firstChild.MergeAttribute("type", "hidden");
    firstChild.MergeAttribute("name", "Ids");
    firstChild.TagRenderMode = TagRenderMode.SelfClosing;
    
    TagBuilder secondChild = new TagBuilder("input");
    secondChild.MergeAttribute("type", "hidden");
    secondChild.MergeAttribute("name", "Ids");
    secondChild.TagRenderMode = TagRenderMode.SelfClosing;
    
    var innerHtml = new MyBufferedHtmlContent();
    innerHtml.Append(firstChild);
    innerHtml.Append(secondChild);
    TagBuilder parent = new TagBuilder("div");
    parent.InnerHtml = innerHtml;
    

提交回复
热议问题