tags:

views:

2938

answers:

4

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.

+2  A: 

I've not tried this, but you can load a control using the LoadControl function:

Control Example = LoadControl("~\\Controls\\MyControl.ascx");

Then you could try rendering the control:

StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Example.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

But make sure that you override VerifyRenderingInServerForm and switch EnableEventValidation to false on the page.

Forget what I wrote above. I went back and tested and you can't call LoadControl because the webmethod is static. Since it's static you don't have a Page object to call... Which means no loading of user controls dynamically.

JaCraig
You are actually mostly right. MyUsercontrol uc = (MyUserControl)Page.LoadControl("/path/to/MyUserControl.ascx"); Then you can either do SomeItem.Controls.Add(uc); or render the control to string as you demonstrated then add the dom item programmatically using jQuery, either works.
Serapth
Actually I don't think that adding the control would be an option in this case. No full postback (no page object or any objects to add the control to), calling from jQuery, etc. But Keltex's approach works.
JaCraig
+1  A: 

This Explanation should have the answers you are looking for. Basically you have to declare the control in the page then LoadControl in the codebehind.

Tacoman667
+8  A: 

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
A: 

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";
Jules