HtmlGenericControl(“br”) rendering twice

二次信任 提交于 2019-11-29 14:02:42

After some testing it looks like the reason is that HtmlGenericControl doesn't support self closing. On server side the HtmlGenericControl("br") is treated as:

<br runat="server"></br>

There is no </br> tag in HTML, so the browser shows it as there are two <br /> tags. Nice way out of this is to create HtmlGenericSelfCloseControl like this (sorry for C# code but you should have no issue with rewritting this in VB.NET):

public class HtmlGenericSelfCloseControl : HtmlGenericControl
{
    public HtmlGenericSelfCloseControl()
        : base()
    {
    }

    public HtmlGenericSelfCloseControl(string tag)
        : base(tag)
    {
    }

    protected override void Render(HtmlTextWriter writer)
    {
        writer.Write(HtmlTextWriter.TagLeftChar + this.TagName);
        Attributes.Render(writer);
        writer.Write(HtmlTextWriter.SelfClosingTagEnd);
    }

    public override ControlCollection Controls
    {
        get { throw new Exception("Self closing tag can't have child controls"); }
    }

    public override string InnerHtml
    {
        get { return String.Empty; }
        set { throw new Exception("Self closing tag can't have inner content"); }
    }

    public override string InnerText
    {
        get { return String.Empty; }
        set { throw new Exception("Self closing tag can't have inner text"); }
    }
}

And use it instead:

pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(New HtmlGenericSelfCloseControl("br"))

As a simpler alternative (if you have reference to the Page) you can try using Page.ParseControl:

pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(Page.ParseControl("br"))
Berkay Turancı

Actually you can use;

pDoc.Controls.Add(new LiteralControl("<br/>"));

Whereas new HtmlGenericControl("br") adds two <br>, this will only add <br/> tag to your HTML so that you just have 1 space line. In this picture I added those breaks with that code block.

Also similar question here: Server control behaving oddly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!