WebPart RenderControl 不呈现内容

发布于 2024-10-26 03:32:55 字数 608 浏览 3 评论 0原文

我有一个自定义 Web 部件,我尝试对其调用 RenderContents 方法,但结果仅包含 Web 部件的周围 div,而不包含任何子控件。

以这个简单的 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."));
    }
  }
}

然后,在 http 处理程序中,我尝试实例化此 Web 部件并调用其 RenderControl 方法。结果是

有谁知道为什么我没有将 CreateChildControls 中的控件也添加到输出中?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

篱下浅笙歌 2024-11-02 03:32:55

这是因为,当您仅实例化一个控件并对其调用 RenderControl 时,而不将其添加到 Controls 集合中,那么它就不是导致所有事件触发的页面生命周期的一部分。

特别是调用 EnsureChildControl 的 PreRendering 不会被调用。

简单的解决方案是像这样重写 Render:

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

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);
}
写给空气的情书 2024-11-02 03:32:55

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

i would suggest to write your code in render method rather than writing in createchild control

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文