【问题标题】:Programmatically load UserControl with reference in web.config以编程方式加载 UserControl 并在 web.config 中引用
【发布时间】:2012-01-21 14:22:14
【问题描述】:

我在 Web.config 中注册用户控件,如下所示。 如何将带有标记名标头的用户控件从代码隐藏动态加载到占位符中? 我使用 ASP.NET 4.0

<configuration>
  <system.web>
    <pages>
      <controls>
        <add tagPrefix="blogUc" src="~/Controls/Header/Header.ascx" tagName="header"/>
      </controls>
    </pages>
  </system.web>
</configuration>

【问题讨论】:

    标签: c# asp.net user-controls web-config ascx


    【解决方案1】:

    这是一篇好文章How to Create Instances of ASP.Net UserControls Programmatically.,不要忘记在代码隐藏文件中引用 UserControl 所在的命名空间。

    // Reference to namespace in Code-Behind file
    using MyNamespace.UserControls;
    
    // In code behind class
    protected MyUserControl userControl1 = null;
    

    【讨论】:

      【解决方案2】:

      您可以通过编程方式从 web.config 中读取 pages Section 并加载您喜欢的控件。

      参考:http://msdn.microsoft.com/en-us/library/system.web.configuration.tagprefixcollection.aspx

      这是可能对您有所帮助的代码。 (注意它会循环遍历所有的 Controls 集合,如果您的控件列表很长,这可能会导致性能问题)

      PagesSection pagesSection = (PagesSection)WebConfigurationManager.GetWebApplicationSection("system.web/pages");
      
      foreach (TagPrefixInfo tag in pagesSection.Controls)
      {
          if (tag.TagName == "header")
          {
              UserControl userControl=  (UserControl) Page.LoadControl(tag.Source);
              PlaceHolder1.Controls.Add(userControl);
              break;
          }
      }
      

      【讨论】:

        【解决方案3】:

        调用TemplateControl.ParseControl方法:

        Control control = TemplateControl.ParseControl("<blogUc:header runat='server' />");
        this.placeHolder.Controls.Add(control);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-25
          • 1970-01-01
          • 2010-09-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-02
          相关资源
          最近更新 更多