Load ascx component using C# code

AlexH picture AlexH · May 8, 2009 · Viewed 14k times · Source

Is there any way that I can use C# to load and then "render" an ascx control?

Essentially I am trying to replace inline ASP with a C# function which will return the same HTML. This would then let me set it as a webmethod so that I can update that section of the page with jQuery, using the same code that generated the original html.

I really need some way of doing this, and this seems like a logical route.

Answer

Keltex picture Keltex · May 8, 2009

You need to create a page in which you render the control:

public static string RenderUserControl(string path)
{
    Page pageHolder = new Page();
    Control viewControl = pageHolder.LoadControl(path);

    pageHolder.Controls.Add(viewControl);
    using(StringWriter output = new StringWriter())
    {
        HttpContext.Current.Server.Execute(pageHolder, output, false);
        return output.ToString();
    }
}

A user control on its own will not render. (This article has some related information from which I borrowed some code).