当我在运行时实例化 ASP.NET 用户控件时,为什么它会忽略 ASCX 文件?
我创建了一个常规 ASP.NET 用户控件,包括 ascx 文件。 例如:
MyUserControl.ascx
MyUserControl.ascx.cs
然后,我尝试在运行时使用类似于以下代码的代码手动呈现控件:
var testMyUserControl = new MyUserControl();
var textWriter =
new HtmlTextWriter(
new System.IO.StringWriter(new StringBuilder()));
testMyUserControl.RenderControl(textWriter);
Console.Write(textWriter.InnerWriter.ToString());
我放入 ASCX 文件中的任何内容似乎都无法呈现 - 无论是静态 HTML 还是任何 .NET 控件。
但是,如果我重写代码隐藏中的 Render() 方法并手动输出内容,它就会渲染。
我在这里缺少什么?
I've created a regular ASP.NET user control, including the ascx file. For example:
MyUserControl.ascx
MyUserControl.ascx.cs
Then I try to render the control manually, at runtime, using code similar to the following code:
var testMyUserControl = new MyUserControl();
var textWriter =
new HtmlTextWriter(
new System.IO.StringWriter(new StringBuilder()));
testMyUserControl.RenderControl(textWriter);
Console.Write(textWriter.InnerWriter.ToString());
Nothing that I put in the ASCX file seems to render - either static HTML or any .NET controls.
However if I override the Render() method in the code-behind and manually output content, it does render.
What am I missing here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要自己进行控制。 如果您需要将其动态添加到页面,您可以这样做:
很可能您希望将其放置在页面的某个部分,因此不要使用 Page.Controls,而是使用占位符:
并使用如下代码:
这是动态添加控件的最佳方式,但如果您可以以声明方式添加控件,那就容易多了。
请记住:如果您要动态添加控件,请务必每次页面加载时重新添加控件。
You don't need to render your control yourself. If you need to add it to the page dynamically, you do it like:
Most likely you'll want to place it in a certain part of the page, so instead of using Page.Controls, use a placeholder:
and use code like this:
This is the best way to add a control dynamically, but if you can do it declaratively instead that would be a lot easier.
Remember: if you're adding the control dynamically, be sure to re-add the control every page load.