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.
1 2 3 4 5 6 7 8 9 10 |
Control myControl = LoadControl("~/MyControl.ascx"); StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter(sb)) { using (HtmlTextWriter tw = new HtmlTextWriter(sw)) { myControl.RenderControl(tw); } } Console.WriteLine(sb); |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
Page page = new Page(); Control myControl = LoadControl("~/MyControl.ascx"); StringBuilder sb = new StringBuilder(); page.Controls.Add(myControl); using (StringWriter sw = new StringWriter(sb)) { Server.Execute(page, sw, false); } Console.WriteLine(sb); |
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.