Removing SPAN-tags around server control

I had to write some ASP.NET server controls for our current SharePoint portal project. We have very nice DIV-based layout and using standard components that generate table and a lot of JavaScript seems to me like an bad idea. I found out that server controls put container tags around their mark-up. I needed my own tags around output and I found a way how to achieve it.

There are two rendering methods I needed to override: RenderBeginTag and RenderEndTag. Be default these methods create <span> and </span> tag before and after web part outout respectively. When creating web parts DIV-tags are created instead SPANs. Now let’s remove these tags. You need only these two simple overrides:

public override void RenderBeginTag(HtmlTextWriter writer)
public override void RenderEndTag(HtmlTextWriter writer)

That’s it.

Liked this post? Empower your friends by sharing it!
Categories: ASP.NET

View Comments (8)

  • Or override the TagKey property (I forget which property to override if its a non-standard HTML element), and possibly AddAttributesToRender if you need to.

  • You can also inherit from Control instead of WebControl/Composite control to avoid your control rendering surrounding divs or spans.

  • An other way to do it:

    public class CustomCheckBox : CheckBox
    protected override void Render(HtmlTextWriter writer)
    // Use custom writer
    writer = new HtmlTextWriterNoSpan(writer);

    // Call base class

    public class HtmlTextWriterNoSpan : HtmlTextWriter
    public HtmlTextWriterNoSpan(TextWriter textWriter)
    : base(textWriter)
    { }

    protected override bool OnTagRender(string name, HtmlTextWriterTag key)
    // Do not render tags
    if (key == HtmlTextWriterTag.Span)
    return false;

    // Otherwise, call the base class (alway true)
    return base.OnTagRender(name, key);

Related Post