【问题标题】:How to access controls collection of dynamically loaded aspx page?如何访问动态加载的aspx页面的控件集合?
【发布时间】:2009-06-27 00:36:22
【问题描述】:

假设我有两个网络表单,A.aspxB.aspx,其中 B.aspx 包含一些简单的网络控件,例如文本框和按钮。

我正在尝试执行以下操作:

当请求 A.aspx 时, 我想动态调用 B.aspx 并将其加载到内存中,并输出 B.aspx 中包含的所有控件的详细信息。

这是我在 A.aspx 的代码隐藏中尝试的:

var compiledType = BuildManager.GetCompiledType("~/b.aspx");
if (compiledType != null)
{
  var pageB = (Page)Activator.CreateInstance(compiledType);
}

foreach (var control in pageB.Controls)
{
    //output some details for each control, like it's name and type...
}

当我尝试上面的代码时,pageB 的控件集合始终为空。

关于如何让它发挥作用的任何想法?

其他一些重要细节:

【问题讨论】:

  • 为什么要访问已执行页面的控制集合?

标签: c# asp.net dynamic webforms


【解决方案1】:

我真的认为您应该提供更多关于您正在尝试做的事情的背景信息。 HttpServerUtility::Execute(String, TextWriter) 将执行一个页面并将结果写入提供的 TextWriter 对象。从那里您可以检查页面的内容,如果生成的 HTML 文档格式正确,您甚至可以通过 .NET XML API 遍历其结构。

您想访问已执行页面的控件集合的原因是什么?

【讨论】:

    【解决方案2】:

    每当我做这样的事情时,我总是不得不使用Page.FindControl or Control.FindControl.

    很遗憾,FindControl 没有递归版本。但是,this blog post 提供了 FindControlRecursive 函数。有了它,您可以遍历容器中的所有控件(可能包括您的 PageB)。

    private Control FindControlRecursive(Control root, string id) 
    { 
        if (root.ID == id)
        { 
            return root; 
        } 
    
        foreach (Control c in root.Controls) 
        { 
            Control t = FindControlRecursive(c, id); 
            if (t != null) 
            { 
                return t; 
            } 
        } 
    
        return null; 
    } 
    

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多