How can I programmatically build a System.Web.UI.P

2019-02-19 10:48发布

I have this code:

public static string RenderView(string path)
{
    Page pageHolder = new Page();
    UserControl viewControl = (UserControl)pageHolder.LoadControl(path);

    pageHolder.Controls.Add(viewControl);

    StringWriter output = new StringWriter();
    HttpContext.Current.Server.Execute(pageHolder, output, false);

    return output.ToString();
}

Which is run from:

    [WebMethod]
    public string GetReportsHTML()
    {
        string output = "";

        output = ViewManager.RenderView("ReportsControl.ascx");

        return output;
    }

This is to test rendering ASCX files and spitting them out of a SOAP/REST service.

Problem is, some controls (runat=server ones) fail if they are not encapsulated in a tag with runat=server.

The solution to that is here, but the solution assumes being inside an ASPX file where I can just edit the markup.

How would I programmatically build a Page, add a Form, set runat=server so that I can follow that solution and add my control to the Form Control?

1条回答
虎瘦雄心在
2楼-- · 2019-02-19 11:16

Have you tried something like this ?

public static string RenderView(string path)
{
    Page pageHolder = new Page();
    System.Web.UI.HtmlControls.HtmlForm formHolder = new System.Web.UI.HtmlControls.HtmlForm();
    pageHolder.Controls.Add(formHolder );

    UserControl viewControl = (UserControl)pageHolder.LoadControl(path);

    formHolder.Controls.Add(viewControl);

    StringWriter output = new StringWriter();
    HttpContext.Current.Server.Execute(pageHolder, output, false);

    return output.ToString();
}

Hope this will help

查看更多
登录 后发表回答