如何以编程方式构建带有 Form 和 UserControl 的 Sy

How can I programmatically build a System.Web.UI.Page with a Form and a UserControl?(如何以编程方式构建带有 Form 和 UserControl 的 System.Web.UI.Page?)

本文介绍了如何以编程方式构建带有 Form 和 UserControl 的 System.Web.UI.Page?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码:

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();
}

运行自:

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

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

        return output;
    }

这是为了测试渲染 ASCX 文件并将它们吐出 SOAP/REST 服务.

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

问题是,如果某些控件(runat=server 的控件)没有封装在带有 runat=server 的标记中,则它们会失败.

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

解决方案是此处,但该解决方案假定位于 ASPX 文件中,我可以在其中编辑标记.

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

我将如何以编程方式构建页面、添加表单、设置 runat=server 以便我可以遵循该解决方案并将我的控件添加到表单控件?

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?

推荐答案

你有没有尝试过这样的事情?

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();
}

希望这会有所帮助

这篇关于如何以编程方式构建带有 Form 和 UserControl 的 System.Web.UI.Page?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何以编程方式构建带有 Form 和 UserControl 的 Sy

基础教程推荐