我有任何ASP.NET控件.我想要HTML字符串如何获取控件的HTML字符串?
这似乎有效.
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(); }
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(); } }
如果您的控件是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()); }