2014-01-08 26 views
4

我正在使用C#中的靜態類,並試圖使用Control.RenderControl()來獲取Control的字符串/標記表示形式。在ASP.NET中人爲觸發頁面事件?

不幸的是,控制(以及所有子控件)使用事件冒泡來填充特定的值,例如,實例化時,則調用以下RenderControl()

public class MyTest : Control 
{ 
    protected override void OnLoad(EventArgs e) 
    { 
     this.Controls.Add(new LiteralControl("TEST")); 
     base.OnLoad(e); 
    } 
} 

我返回一個空字符串,因爲OnLoad()永遠不會被解僱。

有沒有辦法可以調用'假'頁面生命週期?也許使用一些虛擬Page控制?

+0

只是好奇:爲什麼你想要輸出爲字符串有什麼理由?你是否將輸出保存到數據庫或類似的東西,或者它會在某個時候呈現到網頁中?如果您只想執行一些處理或將其集成到手動編寫HTML的其他部分,則通常可以在ASP.NET中執行所有這些操作(例如,使用用於原始HTML的Literal控件,用於其他服務器控件的PlaceHolder控件等)。 – Luaan

+0

@Luaan渲染的標記旨在作爲電子郵件的一部分發送。 – maxp

+2

是的,在這種情況下,除非你真的可以讓一個「真正的」ASPX做同樣的事情,MikeC的答案就是很好。除非使用反射,否則我不認爲有另一種簡單的方法 - 處理頁面生命週期所涉及的方法通常是「內部」或「私有」,而這些方法又稱爲「受保護」的OnLoad等方法。另一方面,Server.Execute非常適合執行HttpHandler。當然,你可以手動調用頁面的IHttpHandler.ProcessRequest,但是你只需要使用更多的代碼來完成與Server.Execute相同的操作:) – Luaan

回答

9

我能夠通過使用Page和本地實例HttpServerUtility.Execute做到這一點:

// Declare a local instance of a Page and add your control to it 
var page = new Page(); 
var control = new MyTest(); 
page.Controls.Add(control); 

var sw = new StringWriter();    

// Execute the page, which will run the lifecycle 
HttpContext.Current.Server.Execute(page, sw, false);   

// Get the output of your control 
var output = sw.ToString(); 

編輯

如果你需要控制一個<form />標籤裏面存在,則只需添加一個HtmlForm轉到頁面,然後將控件添加到該窗體中,如下所示:

// Declare a local instance of a Page and add your control to it 
var page = new Page(); 
var control = new MyTest(); 

// Add your control to an HTML form 
var form = new HtmlForm(); 
form.Controls.Add(control); 

// Add the form to the page 
page.Controls.Add(form);     

var sw = new StringWriter();    

// Execute the page, which will in turn run the lifecycle 
HttpContext.Current.Server.Execute(page, sw, false);   

// Get the output of the control and the form that wraps it 
var output = sw.ToString(); 
+0

非常感謝。我剛剛嘗試過,效果很好。作爲一個附錄,如果有任何控件需要在'

'內,那麼必須調整標準的'Page'類。爲了他人的緣故,我在這裏上傳了源代碼。 http://pastebin.com/3EKwB8sC – maxp

+0

@maxp它比這更簡單,只需新建一個'HtmlForm'並將其添加到頁面即可。然後你將控件添加到'HtmlForm'而不是頁面,並且瞧! – mclark1129

相關問題