How can I programmatically build a System.Web.UI.Page with a Form and a UserControl?

断了今生、忘了曾经 提交于 2019-12-01 07:59:23

问题


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:


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



来源:https://stackoverflow.com/questions/14707826/how-can-i-programmatically-build-a-system-web-ui-page-with-a-form-and-a-usercont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!