gpt4 book ai didi

asp.net - ASP.net 中是否有 after Page_Load 事件

转载 作者:行者123 更新时间:2023-12-03 07:48:50 25 4
gpt4 key购买 nike

所有 Page_Load 事件完成后是否会触发一个事件?

How can i have more than one Page_Load?
When you have user controls.

在我的页面可以呈现之前,我需要我的页面(和所有嵌入式控件)通过完成其 Page_Load 事件来初始化自身。

问题当然是,如果我将代码放入页面的 Page_Load 处理程序中:

MyPage.aspx
--> Page_Load
---> DoSomethingWithUserControl()
UserControl1.ascx
--> Page_Load
---> initialize ourselves now that viewstate has been restored

然后我在 UserControl1 控件准备就绪之前开始访问它。

我需要一种在所有 Page_Load 事件触发之后,但在任何回发事件(例如 Click 事件)触发之前运行代码的方法:

MyPage.aspx
--> Page_Load
UserControl1.ascx
--> Page_Load
---> initialize ourselves now that viewstate has been restored
MyPage.aspx
--> Page_AfterLoad
---> DoSomethingWithUserControl()

查看 MSDN 中的页面生命周期,似乎在所有 Page_Load 完成后都无法引发事件:

enter image description here

有没有办法在所有 Page_Loads 完成后之后引发?

最佳答案

Page_LoadComplete是在加载所有控件后引发的事件

请记住,Init 事件首先由所有子控件触发,并且当所有控件都已初始化时,就会引发页面的 Init 事件。 Load 事件以相反的方式工作,页面首先引发 Load 事件,然后每个子控件引发其自己的 Load 事件。最后引发 LoadComplete请注意,只有在设计时创建控件时才是如此,当动态创建控件时,它们(遗憾的是)并不严格遵循此方法。

来自 MSDN:

If controls are created dynamically at run time or declaratively within templates of data-bound controls, their events are initially not synchronized with those of other controls on the page. For example, for a control that is added at run time, the Init and Load events might occur much later in the page life cycle than the same events for controls created declaratively. Therefore, from the time that they are instantiated, dynamically added controls and controls in templates raise their events one after the other until they have caught up to the event during which it was added to the Controls collection.

看一下:

(来源:http://msdn.microsoft.com/en-us/library/ms178472.aspx)

enter image description here

编辑 1

为了满足您的所有要求:

i need a way to run code after all Page_Load events have fired, but before any postback events (e.g. Click events) have fired:

我认为最简单的方法是在用户控件中声明一个自定义事件并在加载控件后触发它,然后在您的 ASPX 中订阅该事件

用户控制

    public event Action LoadCompleted = delegate { };

protected void Page_Load(object sender, EventArgs e)
{
this.LoadCompleted();
}

ASPX 页面

    protected void Page_Load(object sender, EventArgs e)
{
this.myUserControl.LoadCompleted += () =>
{
// do somethign interesting
this.lblMessage.Text = DateTime.Now.ToString();
};
}

关于asp.net - ASP.net 中是否有 after Page_Load 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11235062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com