Seven years late, but it deserves to be shared.
The common solution - StringBuilder in StringWriter in HtmlWriter in RenderControl - is good. But there are some gotchas that I, unfortunately, have come across while trying to do the same. Some controls will throw errors if they are not inside the Page , and some will throw errors if they are not inside the <form> with runat="server" . The ScriptManager control demonstrates both of these behaviors.
In the end, I found a workaround here. Its essence is mainly to create an instance of a new page and form before performing the authorβs work:
Page page = new Page(); page.EnableEventValidation = false; HtmlForm form = new HtmlForm(); form.Name = "form1"; page.Controls.Add(form1); MyControl mc = new MyControl(); form.Controls.Add(mc); StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); HtmlTextWriter writer = new HtmlTextWriter(sw); page.RenderControl(writer); return sb.ToString();
Unfortunately, this gives you more markup than you really need (since it includes a dummy form). And the ScriptManager still fails for some secret reason that I haven't puzzled yet. Honestly, this is a lot of trouble and is not worth doing; the whole point of generating controls in the code lock is such that in the end you donβt have to bother with markup.
Reikim Jul 24 '15 at 21:03 2015-07-24 21:03
source share