简体   繁体   中英

WebPart RenderControl doesn't render contents

I have a custom web part that I am trying to call the RenderContents method on, but the results only contains the surrounding div for the web part, and not any child controls.

Take for example this simple web part:

namespace MyWebParts
{
  public class MyTestWebPart : WebPart
  {
    public MyTestWebPart()
    {
      this.CssClass = "myTestWebPart";
    }
    protected override void CreateChildControls()
    {
      base.CreateChildControls();

      this.Controls.Add(new LiteralControl("Nothing here yet."));
    }
  }
}

Then, in an http handler, I'm trying to instantiate this web part and call its RenderControl method. The result is <div class="myTestWebPart"></div> .

Does anyone know why I am not getting my controls from CreateChildControls also added to the output?

It's because when you're only instantiating a control and calling RenderControl on it, without it being added to a Controls collection, then it's not part of the Page lifecycle which causes all the events to fire.

In particular the PreRendering which calls EnsureChildControl isn't called.

The easy solution is to override Render like this:

protected override void Render(HtmlTextWriter writer)
{
  EnsureChildControls();
  base.Render(writer);
}

我建议用render方法编写代码,而不是用createchild控件编写代码

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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