如何以编程方式构建带有 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)