在ASP.net中有一个后Page_Load事件

前端之家收集整理的这篇文章主要介绍了在ASP.net中有一个后Page_Load事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有在所有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事件触发后,但在任何回发事件(例如点击事件)触发之前运行代码

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

查看MSDN中的页面生命周期,看起来没有办法在所有Page_Loads完成后引发事件:

有没有办法提出一个后,所有的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)

编辑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:

我认为最简单的方法是在用户控件中声明一个自定义事件,并在加载控件后触发它,然后jus在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();
        };
    }
原文链接:https://www.f2er.com/aspnet/254092.html

猜你在找的asp.Net相关文章