views:

46

answers:

1

I want to use an ascx as a template, and render it programatically, using the resulting html as the return value of an ajax method.

Page pageHolder = new Page();
MyUserControl ctlRender = (MyUserControl)pageHolder.LoadControl(typeof(MyUserControl),null);

pageHolder.Controls.Add(ctlRender);
System.IO.StringWriter swOutput = new System.IO.StringWriter();
HttpContext.Current.Server.Execute(pageHolder, swOutput, false);
return swOutput.ToString();

This all executes, and the Page Load event of the user control fires, but the StringWriter is always empty. I've seen similar code to this in other examples, what am I missing?

+1  A: 

Have you tried this:

public string RenderControl(Control ctrl) 
{
    StringBuilder sb = new StringBuilder();
    StringWriter tw = new StringWriter(sb);
    HtmlTextWriter hw = new HtmlTextWriter(tw);

    ctrl.RenderControl(hw);
    return sb.ToString();
}

Taken directly from the article here:

ASP.NET Tip: Render Control into HTML String

Justin Niessner