ASP.NET如何将控件渲染为HTML?
我有任何ASP.NET控件。 我想要的HTMLstring如何获得控件的HTMLstring?
这似乎工作。
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(); }
如果您的控件是一个Web用户控件,那么您可以通过其他页面或处理程序获取到的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()); }
如果控制不是页面的一部分, David Basarab
接受的答案将不起作用。 a7drew
的答案似乎是不必要的复杂 – 无需在Context
或Server.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(); } }