1

我开发了一个自定义用户控件。对于特定的需要,我必须从其中的 usercontrol 生成 html 并仅在页面正文中显示它。

我认为可能会重载 RenderControl(HtmlTextWriter writer) 但我不知道如何。

谢谢

4

1 回答 1

2

您可以在内存中呈现控件,将其放在字符串上,然后按照您所说的在页面上的某个位置打印此字符串。这是加载控件并将其呈现在内存中的代码,然后将结果存储在字符串中。

    // load the control
    var oTesto = Page.LoadControl("Testo.ascx");

    // here you need to run some initialization of your control
    //  because the page_load is not loading now.

    // a string writer to write on it
    using(TextWriter stringWriter = new StringWriter())
    {
      // a html writer
      using(HtmlTextWriter GrapseMesaMou = new HtmlTextWriter(stringWriter))
      {
        // now render the control inside the htm writer
        oTesto.RenderControl(GrapseMesaMou);

        // here is your control rendered output.
        strBuild = stringWriter.ToString();
      }
    }

要捕获控件的呈现,您可以将Render用作:

protected override void Render(HtmlTextWriter writer)
{
    System.IO.StringWriter stringWriter = new System.IO.StringWriter();

    HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);

    // now the control is inside the htmlWriter as final rendered text
    base.Render(htmlWriter);

    // here is how to make the control render itself
    // base.Render(writer);
}

您将渲染放在您的控件类中。

于 2012-08-03T08:03:51.330 回答