2010-08-31 23 views
1

我想動態添加一個用戶控件,我創建到加載後的aspx頁面。 我試着發送一個ajax請求到一個使用RenderControl函數的處理程序併發送回控件的html。我使用javascript將它附加到DOM。加載頁面後添加用戶控件

問題是,一些控件必須通過其Page_Load函數,並且在使用RenderControl函數時不會發生。

有沒有人有任何想法我該怎麼做?

+0

出於好奇,爲什麼你必須在頁面加載後添加它?在頁面加載後,你在「客戶端世界」(html,javasript)。我不能想象從客戶端添加服務器控件的方法。你需要做一些非常棘手的問題/ hacky(添加一個控件到一個updatepanel,然後立即觸發trigger1) – RPM1984 2010-08-31 12:22:19

+0

我在後臺加載整個UI,我不希望客戶端感覺到這(這會減慢速度瀏覽器)。我希望客戶端能夠看到頁面的一部分,並在完成渲染後繼續渲染UI的其餘部分(在頁面加載後)。 – Anat 2010-08-31 12:40:41

回答

0

試試這個:

System.Web.UI.Page page = new System.Web.UI.Page(); 
CustomUserControl userControl = page.LoadControl("~/control.ascx") as CustomUserControl; 
if (userControl == null) 
{ 
//error 
} 

userControl.ArticleId = id; 
//call any other properties or methods you need 

page.Controls.Add(userControl); 
System.IO.StringWriter sw = new System.IO.StringWriter(); 
HttpContext.Current.Server.Execute(page, sw, false); 
responseString = sw.ToString(); 

希望這會有幫助!

+0

謝謝,它工作! – Anat 2010-08-31 13:44:17

0

我不認爲你可以這樣做。

您的控件不會通過它們的Page_Load,因爲它們不會添加到任何控件中。你所做的只是渲染他們的html(使用RenderControl)並使用javascript加載它。 Page_Load事件沒有地方。

我會用的UpdatePanel以這種方式來代替:

<asp:UpdatePanel> 
    <ContentTemplate> 
     <asp:Panel ID="pnlDynamic" /> 
    </ContentTemplate> 
</asp:UpdatePanel> 

,然後在後面的代碼添加動態控件面板

pnlDynamic.Controls.Add(new YourControl());