ASP.NET 中的动态加载控件和持久性

发布于 2024-09-17 23:13:22 字数 810 浏览 4 评论 0原文

我正在 Page_Load 事件中加载一系列控件。但是,我必须在每次页面加载时重新创建这些控件,这意味着将它们的数据存储在其他地方。这很麻烦。

protected void Page_Load(object sender, EventArgs e)
{
   MyControl control = (MyControl)LoadControl(...);
   control.Initialize(GlobalClass.controlData);
   //^gives the control the data it had previously.  
   //Or use ViewState["controlData"] if serializable.
   Controls.Add(control);
}

我觉得我应该使用 if (!IsPostBack) {},但我不知道如何使用,也不知道为什么。

相反,如果我将控件放入标记中,那么控件似乎会保持持久性。例如,标记中的按钮将记住对其 Text 属性的任何更改(我认为?)。

<asp:Button ID="buttonText" runat="server" 
            Text="Text Segment" onclick="buttonText_Click" />

如何通过动态添加的控件(例如通过标记添加的控件)保持某种持久性?这将为我节省很多工作和挫败感。

谢谢。

(我已经编写了一小段时间的代码,但是我做的 ASP.NET 越多,我就越困惑。这与我对学习工作的理解完全相反:-P。)

I am loading a series of controls in the Page_Load event. However, I have to recreate those controls each page load, which means storing their data elsewhere. This is cumbersome.

protected void Page_Load(object sender, EventArgs e)
{
   MyControl control = (MyControl)LoadControl(...);
   control.Initialize(GlobalClass.controlData);
   //^gives the control the data it had previously.  
   //Or use ViewState["controlData"] if serializable.
   Controls.Add(control);
}

I feel like I should be using if (!IsPostBack) {}, but I don't know how, or why.

In contrast, if I place the controls into the markup, then the controls seem to stay persistent. For example, a button in mark-up will remember any changes to its Text property (I think?).

<asp:Button ID="buttonText" runat="server" 
            Text="Text Segment" onclick="buttonText_Click" />

How do I maintain some sort of persistence with dynamically added controls, like controls added via mark-up? This would save me much work and frustration.

Thanks.

(I've coded for a small eternity, but the more I do ASP.NET, the more confused I become. Which is exactly the opposite of what how I understood learning to work :-P.)

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

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

发布评论

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

评论(2

唠甜嗑 2024-09-24 23:13:22

对于动态加载的控件,如果在 Page_Init 事件期间加载它们,则可以将它们添加到 ViewState,并且它们将能够保留从 PostBack 到 PostBack 的状态。

For dynamically loaded controls, if you load them during the Page_Init event, you can then add them to the ViewState and they will be able to retain state from PostBack to PostBack.

ゃ懵逼小萝莉 2024-09-24 23:13:22

我明白你的意思。是的,这很麻烦,但这就是无状态技术的工作原理。

没有办法实现与静态控件(放入 HTML 标记中的控件)相同的行为。

按照我在此答案中给出的提示进行操作:

访问动态创建的控件 (c#)

I understand your point. Yes, this is cumbersome, but that's how a stateless technology works.

There's no way of achieving the same bahaviour of static controls (the ones that you put in the HTML markup).

Follow the tips I gave in this answer:

Accessing controls created dynamically (c#)

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