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.
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.
Where do these go?
spanx dude – solved my headache :)
This saved me some time today, so thank you very much, helpful article.
Hi,
I would like to know where you add these two functions? In the .aspx.cs page or the .aspx page?
This code goes to class file of server control.
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
base.Render(writer);
}
}
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);
}
}