Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops.

HowTo: Control the rendered Html tag on your custom, composite server controls

1 min read

Normally when you want to achieve that your custom server control is rendered inside a specific HTML tag you don't override the Render method, but you do something like
public class MySrvControl : WebControl, INamingContainer
{
public MySrvControl() : base(HtmlTextWriterTag.Div)
{
...
}

...

}

Now most often you'll probably have a composite control, meaning that you are aggregating a couple of already existing controls inside your custom server control, providing some further functionality. In such a case, the .Net framework provides the CompositeControl class which should be inherited in that case:
public class MySrvControl : CompositeControl
{
public MySrvControl() : base(HtmlTextWriterTag.Div)
{
...
}

...

}
Note, you don't need the INamingContainer marker interface any more, because it's already done by the CompositeControl. The line "base(HtmlTextWriterTag.Div) however will give you a compiler error, since there is no constructor on the CompositeControl which is taking parameters. So to still provide the same rendering functionality, you simply add
public class MySrvControl : CompositeControl
{
public MySrvControl()
{
...
}

protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Div;
}
}

...

}

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus