2008-09-12 125 views

回答

39

這似乎工作。

public string RenderControlToHtml(Control ControlToRender) 
{ 
    System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
    System.IO.StringWriter stWriter = new System.IO.StringWriter(sb); 
    System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter); 
    ControlToRender.RenderControl(htmlWriter); 
    return sb.ToString(); 
} 
+6

StringWriter和HtmlTextWriter都實現了IDisposable,因此您可能想要將它們包裝在using(){}塊中。另外,將它作爲'Control'的擴展方法可能會很有用,因此您可以從實例成員中調用它。 – 2012-11-09 15:44:42

+1

@David,你是如何最終呈現一個ascx文件到HTML?我嘗試了上面的方法,但總是得到「對象引用未設置爲對象的實例」,並說我所引用的用戶控件不是實例。我們應該如何在Windows窗體或控制檯應用程序中使用它? – Princa 2013-04-30 19:28:53

+1

默認的StringWriter()構造函數創建一個新的字符串構建器,所以前兩行可以用System.IO.StringWriter來替換stWriter = new System.IO.StringWriter(); – Spongeboy 2014-04-09 00:53:26

6

如果你的控制是一個網絡用戶的控制,這是你可以得到它從另一個頁面或處理程序發出的HTML:

public void GetHtmlFromMySweetControl(HttpContext context) 
{ 
    HttpRequest httpRequest = context.Request; 
    HttpResponse httpResponse = context.Response; 

    string foo = httpRequest["foo"]; 

    Page pageHolder = new Page(); 
    string path = "~/usercontrols/MySweetControl.ascx"; 
    MySweetControl ctrl = (MySweetControl)pageHolder.LoadControl(path); 
    ctrl.BindProducts(foo); 
    pageHolder.Controls.Add(ctrl); 

    StringWriter sw = new StringWriter(); 
    context.Server.Execute(pageHolder, sw, false); 
    httpResponse.Write(sw.ToString()); 
} 
6
通過 David Basarab

接受的答案是行不通的,如果控制不是頁面的一部分。 a7drew的答案似乎不必要複雜 - 無需在ContextServer.Execute

private string RenderControl() 
{ 
    var sb = new System.Text.StringBuilder(); 
    using (var stWriter = new System.IO.StringWriter(sb)) 
    using (var htmlWriter = new HtmlTextWriter(stWriter)) 
    { 
     var p = new Page(); 
     var ctrl = (YourControl)p.LoadControl("~/controls/building blocks/YourControl.ascx"); 
     ctrl.Visible = true; 

     // do your own init logic if needed 

     p.Controls.Add(ctrl); 
     ctrl.RenderControl(htmlWriter); 
     return sb.ToString(); 
    } 
}