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.
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).
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With