【问题标题】:Find ContentPlaceHolders in Master page在母版页中查找 ContentPlaceHolders
【发布时间】:2013-02-10 00:19:40
【问题描述】:

我正在寻找一种动态加载母版页的方法,以便在其中获取 ContentPlaceHolders 的集合。

我希望不必加载页面对象来分配母版页,然后才能访问它的控件,但如果这是唯一的方法,我会很乐意使用它。这是我希望它会起作用的方式:

        Page page = new Page();
        page.MasterPageFile = "~/home.master";
        foreach (Control control in page.Master.Controls)
        {
            if (control.GetType() == typeof(ContentPlaceHolder))
            {
                // add placeholder id to collection
            }
        }

但是page.Master 抛出空引用异常。它似乎只在页面生命周期中创建实际页面的某个时间点加载。

我什至想过在 Page_Init() 上动态更改当前页面的 MasterPageFile,读取所有 ContentPlaceHolders 然后将原始 MasterPageFile 分配回去,但这太可怕了!

有没有办法将母版页加载到独立于实际页面的内存中,以便我可以访问它的属性?

我最后的手段可能会涉及解析 ContentPlaceHolders 的母版页内容,这不是那么优雅,但可能会更快一些。

有人可以帮忙吗?非常感谢。

【问题讨论】:

    标签: c# asp.net master-pages


    【解决方案1】:

    您应该能够使用 LoadControl 加载母版页并枚举 Controls 集合。

      var site1Master = LoadControl("Site1.Master");
    

    要查找内容控件,您需要递归搜索控件集合。这是一个快速而肮脏的例子。

    static class WebHelper
    {
      public static IList<T> FindControlsByType<T>(Control root) 
        where T : Control
      {
        List<T> controls = new List<T>();
        FindControlsByType<T>(root, controls);
        return controls;
      }
    
      private static void FindControlsByType<T>(Control root, IList<T> controls)
        where T : Control
      {
        foreach (Control control in root.Controls)
        {
          if (control is T)
          {
            controls.Add(control as T);
          }
          if (control.Controls.Count > 0)
          {
            FindControlsByType<T>(control, controls);
          }
        }
      }
    }
    

    上面可以这样使用

      // Load the Master Page
      var site1Master = LoadControl("Site1.Master");
    
      // Find the list of ContentPlaceHolder controls
      var controls = WebHelper.FindControlsByType<ContentPlaceHolder>(site1Master);
    
      // Do something with each control that was found
      foreach (var control in controls)
      {
        Response.Write(control.ClientID);
        Response.Write("<br />");
      }
    

    【讨论】:

    • 太棒了,这正是我想要做的,而且以一种更优雅的方式。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 2012-06-20
    • 2012-05-18
    • 2011-04-12
    相关资源
    最近更新 更多