Home > .NET, C# > Stripping span tag from WebControl

Stripping span tag from WebControl

September 15th, 2008
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

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()
{ }
Share and Bookmark:
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • blogmarks
  • DotNetKicks
  • E-mail this story to a friend!
  • Furl
  • Live
  • Reddit
  • Slashdot
Did you found this article helpful?
Buy me a coffee :)

.NET, C# , , ,

  1. February 27th, 2009 at 04:39 | #1

    You have good site

  2. TravisM
    August 5th, 2009 at 15:14 | #2

    Thanks! I was using MyBase.Render(writer) when I should have been using MyBase.RenderContents(writer)

  3. Neha
    July 22nd, 2010 at 19:19 | #3

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

  4. December 5th, 2010 at 12:28 | #4

    how are you?

    Definitely gonna recommend this post to a few friends

  5. Roberts
    October 20th, 2011 at 14:36 | #5

    Thanks for this!

  1. No trackbacks yet.