简体   繁体   English

如何在 .NET (C#) 中获取 UserControl 的 HTML 输出?

[英]How do I get the HTML output of a UserControl in .NET (C#)?

If I create a UserControl and add some objects to it, how can I grab the HTML it would render?如果我创建一个 UserControl 并向其添加一些对象,我如何获取它会呈现的 HTML?

ex.前任。

UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());

// ...something happens

return strHTMLofControl;

I'd like to just convert a newly built UserControl to a string of HTML.我只想将新建的 UserControl 转换为 HTML 字符串。

You can render the control using Control.RenderControl(HtmlTextWriter) .您可以使用Control.RenderControl(HtmlTextWriter)呈现控件。

Feed StringWriter to the HtmlTextWriter .StringWriter馈送到HtmlTextWriter

Feed StringBuilder to the StringWriter .StringBuilderStringWriter

Your generated string will be inside the StringBuilder object.您生成的字符串将位于StringBuilder对象内。

Here's a code example for this solution:这是此解决方案的代码示例:

string html = String.Empty;
using (TextWriter myTextWriter = new StringWriter(new StringBuilder()))
{
    using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
    {
        myControl.RenderControl(myWriter);
        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();

Seven years late, but this deserves to be shared.晚了七年,但这值得分享。

The generally accepted solution - StringBuilder into StringWriter into HtmlWriter into RenderControl - is good.普遍接受的解决方案 - StringBuilderStringWriterHtmlWriterRenderControl - 很好。 But there are some gotchas, which I unfortunately ran across while trying to do the same thing.但是有一些问题,不幸的是我在尝试做同样的事情时遇到了这些问题。 Some controls will throw errors if they're not inside of a Page , and some will throw errors if they're not inside of a <form> with runat="server" .如果某些控件不在Page ,则它们会抛出错误,而如果它们不在带有runat="server"<form>内,则某些控件会抛出错误。 The ScriptManager control exhibits both of these behaviours. ScriptManager 控件表现出这两种行为。

I eventually found a workaround here. 我最终在这里找到了解决方法。 The gist of it is basically just instantiating a new Page and Form before doing the writer work:它的要点基本上只是在做作者工作之前实例化一个新的页面和表单:

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();

Unfortunately, this gives you more markup than you actually need (since it includes the dummy form).不幸的是,这为您提供了比实际需要更多的标记(因为它包含虚拟表单)。 And the ScriptManager will still fail for some arcane reason I haven't puzzled out yet.而且 ScriptManager 仍然会因为一些我还没有弄清楚的神秘原因而失败。 Honestly, it's a whole lot of trouble and not worth doing;老实说,这很麻烦,不值得做; the whole point of generating controls in the code-behind is so that you don't have to fiddle around with the markup, after all.毕竟,在代码隐藏中生成控件的全部意义在于,您不必摆弄标记。

override the RenderControl method覆盖 RenderControl 方法

protected override void Render(HtmlTextWriter output)
{       
   output.Write("<br>Message from Control : " + Message);       
   output.Write("Showing Custom controls created in reverse" +
                                                    "order");         
   // Render Controls.
   RenderChildren(output);
}

This will give you access to the writer which the HTML will be written to.这将使您可以访问将写入 HTML 的编写器。

You may also want to look into the adaptive control architecture of asp.net adaptive control architecture of asp.net where you can 'shape' the default html output from controls.您可能还想查看 asp.net自适应控制架构的自适应控制架构,您可以在其中“塑造”控件的默认 html 输出。

调用它的.RenderControl()方法。

You could utilize the HttpServerUtility.Execute Method, available through HttpContext.Current.Server.Execute :您可以使用HttpServerUtility.Execute方法,可通过HttpContext.Current.Server.Execute

var page = new Page();
var myControl = (MyControl)page.LoadControl("mycontrol.ascx");
myControl.SetSomeProperty = true;
page.Controls.Add(myControl);
var sw = new StringWriter();
HttpContext.Current.Server.Execute(page, sw, preserveForm: false);

The benefit would be that you also trigger the Page_Load event of your user control.好处是您还可以触发用户控件的 Page_Load 事件。

MSDN documentation can be found here: https://msdn.microsoft.com/en-us/library/fb04e8f7(v=vs.110).aspx . MSDN 文档可以在这里找到: https : //msdn.microsoft.com/en-us/library/fb04e8f7(v=vs.110).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM