Skip to content Skip to sidebar Skip to footer

Htmlgenericcontrol("br") Rendering Twice

I'm adding some content to a given web page from code behind. When I want to add a break after some text, I try to do that this way: pDoc.Controls.Add(New Label With {.Text = 'what

Solution 1:

Actually you can use;

pDoc.Controls.Add(newLiteralControl("<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.

enter image description here

Also similar question here: Server control behaving oddly

Solution 2:

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:

<brrunat="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):

publicclassHtmlGenericSelfCloseControl : HtmlGenericControl
{
    publicHtmlGenericSelfCloseControl()
        : base()
    {
    }

    publicHtmlGenericSelfCloseControl(string tag)
        : base(tag)
    {
    }

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

    publicoverride ControlCollection Controls
    {
        get { thrownew Exception("Self closing tag can't have child controls"); }
    }

    publicoverridestring InnerHtml
    {
        get { return String.Empty; }
        set { thrownew Exception("Self closing tag can't have inner content"); }
    }

    publicoverridestring InnerText
    {
        get { return String.Empty; }
        set { thrownew 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"))

Post a Comment for "Htmlgenericcontrol("br") Rendering Twice"