Capture the HTML output from a custom server control in ASP.NET

Custom server controls do great job. A complex page can easily be split into many controls. In this way it becomes easier to support after that. Used in a page, a server control follows the whole page life cycle.

Sometimes you will need just to get the HTML output from a server control for a different usage like sending it by an e-mail. So what can you do?  There is a method called RenderControl, which renders a control using a HtmlTextWriter object. We can simply load the control using the LoadControl method and then use RenderControl.

But the output is not what we really want. It contains only the static HTML tags. The server controls inside our control are not rendered. Why? Because in our way, the control does not follow the page life cycle. So, what we should do is to add it to a page.

Server.Execute method executes an IHttpHandler object and writes the output using a TextWriter object. In this way we follow the whole page life cycle so our control will render everything inside it.