WebPart RenderControl 不呈现内容
我有一个自定义 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为,当您仅实例化一个控件并对其调用 RenderControl 时,而不将其添加到 Controls 集合中,那么它就不是导致所有事件触发的页面生命周期的一部分。
特别是调用 EnsureChildControl 的 PreRendering 不会被调用。
简单的解决方案是像这样重写 Render:
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:
我建议在 render 方法中编写代码,而不是在 createchild 控件中编写
i would suggest to write your code in render method rather than writing in createchild control