如果我创建一个UserControl并向其添加一些对象,我如何获取它将呈现的HTML?
恩.
UserControl myControl = new UserControl(); myControl.Controls.Add(new TextBox()); // ...something happens return strHTMLofControl;
我想将新构建的UserControl转换为HTML字符串.
您可以使用渲染控件Control.RenderControl(HtmlTextWriter)
.
喂StringWriter
到HtmlTextWriter
.
喂StringBuilder
到StringWriter
.
生成的字符串将在StringBuilder
对象内.
以下是此解决方案的代码示例:
StringBuilder myStringBuilder = new StringBuilder(); TextWriter myTextWriter = new StringWriter(myStringBuilder); HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter); myControl.RenderControl(myWriter); string html = myTextWriter.ToString();
//render control to string StringBuilder b = new StringBuilder(); HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b)); this.LoadControl("~/path_to_control.ascx").RenderControl(h); string controlAsString = b.ToString();
UserControl uc = new UserControl(); MyCustomUserControl mu = (MyCustomUserControl)uc.LoadControl("~/Controls/MyCustomUserControl.ascx"); TextWriter tw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(tw); mu.RenderControl(hw); return tw.ToString();
迟了七年,但值得分享.
普遍接受的解决方案- StringBuilder
成StringWriter
成HtmlWriter
成RenderControl
-好.但是有一些陷阱,我不幸在试图做同样的事情时跑了过来.如果某些控件不在a中Page
,则会抛出错误,如果某些控件不在with中,则会抛出错误
runat="server"
.ScriptManager控件展示了这两种行为.
我最终在这里找到了解决方法.它的要点基本上只是在做作者工作之前实例化一个新的页面和表单:
Page page = new Page();
page.EnableEventValidation = false;
HtmlForm form = new HtmlForm();
form.Name = "form1";
page.Controls.Add(form1);
MyControl mc = new MyControl();
form.Controls.Add(mc);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
page.RenderControl(writer);
return sb.ToString();
不幸的是,这给你提供了比实际需要更多的标记(因为它包含虚拟形式).而ScriptManager仍然会因为某些神秘的原因而失败,我还没有感到困惑.老实说,这是一个很大的麻烦,不值得做; 毕竟,在代码隐藏中生成控件的全部意义在于,您无需使用标记.