简体   繁体   English

WebPart RenderControl不呈现内容

[英]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. 我有一个自定义Web部件,我试图调用RenderContents方法,但结果只包含Web部件的周围div,而不是任何子控件。

Take for example this simple web part: 以这个简单的Web部分为例:

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. 然后,在一个http处理程序中,我试图实例化此Web部件并调用其RenderControl方法。 The result is <div class="myTestWebPart"></div> . 结果是<div class="myTestWebPart"></div>

Does anyone know why I am not getting my controls from CreateChildControls also added to the output? 有谁知道为什么我没有从CreateChildControls获取我的控件也添加到输出?

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. 这是因为当你只是实例化一个控件并在其上调用RenderControl时,如果它没有被添加到Controls集合中,那么它就不是Page生命周期的一部分,它会导致触发所有事件。

In particular the PreRendering which calls EnsureChildControl isn't called. 特别是不调用调用EnsureChildControl的PreRendering。

The easy solution is to override Render like this: 简单的解决方案是覆盖Render,如下所示:

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

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

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

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