Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load ascx component using C# code

Tags:

c#

asp.net

ascx

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.

like image 490
AlexH Avatar asked May 08 '09 18:05

AlexH


2 Answers

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).

like image 118
Keltex Avatar answered Oct 06 '22 00:10

Keltex


Keltex's answer was the only that worked for me since i was working with nested user-controls. Additionally, if you would want to pass parameters to your user control you can do so by:

_MyNameSpace_MyUserControl viewcontrol = (_MyNameSpace_MyUserControl) pageHolder.LoadControl(path);

viewcontrol.MyParam = "My value";
like image 36
Jules Colle Avatar answered Oct 05 '22 23:10

Jules Colle