2012-01-21 10 views
0

我在Web.config中註冊usercontrols如下。 我如何動態加載usercontrol與標記名頭從代碼隱藏到佔位符? 我使用ASP.NET 4.0編程加載UserControl在web.config中的引用

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

回答

0

您可以以編程方式從web.config讀取頁面部分並加載您喜歡的控件。

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

下面是代碼,可以幫助你。 (注意:通過所有控件集合的循環,如果你有控制一長串這可能是一個性能問題)

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; 
    } 
} 
0

調用TemplateControl.ParseControl方法:

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