Jeremy
Jeremy

Reputation: 46330

Render a user control ascx

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?

Upvotes: 1

Views: 4601

Answers (2)

landi
landi

Reputation: 343

You always have to use something like this.Controls.Add(TemplateControl.LoadControl("~/PathTo/YourControl.ascx")

The reason is, that there is no internal mapping of Types to there ascx-file (only the other way arround). So this means if you initialize new YourControl(), it will not do anything you defined in the ascx part. If you would have

protected override void protected override void Render(HtmlTextWriter output) {
    output.WriteLine("Test");
} 

this would give you "Test" in the place you rendered your control to.

Upvotes: 0

Justin Niessner
Justin Niessner

Reputation: 245399

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

Upvotes: 3

Related Questions