Stripping span tag from WebControl

When I started developing web controls which are created by CreateChildControls method i run into problem that this control is surrounded by span tag.

[ToolboxData("<{0}:ExtendedLabel runat=\"server\" Text=\"Label\" />")]
public class ExtendedLabel : WebControl, INamingContainer
{
  protected override void CreateChildControls()
  {
    Label label = new Label();
    label.Text = this.Text;
    this.Controls.Add (label);
  }
}

This example will product not so nice HTML code:

<span id=?ExtendedLabel?>
  <span name=?ExtendedLabel:Label?>Test string</span>
</span>

The first label come from RenderBeginTag method which contains by default span tag. What you can do is to override both RenderBeginTag and RenderEndTag.

protected override void RenderBeginTag(HtmlTextWriter writer)
{
  writer.Text = writer.Text + "<div id=\"myTag\">";
}
protected override void RenderBeginTag(HtmlTextWriter writer)
{
  writer.Text = writer.Text + "</div>";
}

Or remove this tag completely by overriding Render method.

Original:

protected override void Render(HtmlTextWriter writer)
{
  this.RenderBeginTag(writer);
  this.RenderContents(writer);
  this.RenderEndTag(writer);
}

New:

protected override void Render(HtmlTextWriter writer)
{
  this.RenderContents(writer);
}

In these examples you have full control over behavior of the control. These is another possibility how to change or remove the outlining tag. You can extend your web control from another class.

protected ExtendedLabel () : base()
{ }

6 thoughts on “Stripping span tag from WebControl

  1. Neha

    Thanks a lot. I was also using Mybase.Render(writer) instead of Mybase.RenderContents(writer). This article has been very helpful.

  2. passwords

    That is very interesting, You are an excessively professional blogger.

    I have joined your rss feed and look forward to in the hunt
    for extra of your great post. Also, I have shared your
    site in my social networks

Leave a Reply

Your email address will not be published. Required fields are marked *