当我在运行时实例化 ASP.NET 用户控件时,为什么它会忽略 ASCX 文件?

发布于 2024-07-11 00:04:36 字数 548 浏览 9 评论 0原文

我创建了一个常规 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 技术交流群。

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

发布评论

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

评论(1

ˇ宁静的妩媚 2024-07-18 00:04:36

您不需要自己进行控制。 如果您需要将其动态添加到页面,您可以这样做:

UserControl myControl = (UserControl) Page.LoadControl("~/Controls/MyControl.ascx");
Page.Controls.Add(myControl);

很可能您希望将其放置在页面的某个部分,因此不要使用 Page.Controls,而是使用占位符:

<asp:Placeholder ID="myPlaceHolder" runat="server" />

并使用如下代码:

myPlaceholder.Controls.Add(myControl);

这是动态添加控件的最佳方式,但如果您可以以声明方式添加控件,那就容易多了。

<%@ Register TagPrefix="my" TagName="Control" Src="~/Controls/MyControl.ascx" %>

<my:Control ID="myControl" runat="server" />

请记住:如果您要动态添加控件,请务必每次页面加载时重新添加控件

You don't need to render your control yourself. If you need to add it to the page dynamically, you do it like:

UserControl myControl = (UserControl) Page.LoadControl("~/Controls/MyControl.ascx");
Page.Controls.Add(myControl);

Most likely you'll want to place it in a certain part of the page, so instead of using Page.Controls, use a placeholder:

<asp:Placeholder ID="myPlaceHolder" runat="server" />

and use code like this:

myPlaceholder.Controls.Add(myControl);

This is the best way to add a control dynamically, but if you can do it declaratively instead that would be a lot easier.

<%@ Register TagPrefix="my" TagName="Control" Src="~/Controls/MyControl.ascx" %>

<my:Control ID="myControl" runat="server" />

Remember: if you're adding the control dynamically, be sure to re-add the control every page load.

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