Asp.net2.0页面执行顺序

本文详细解析了ASP.NET页面及包含MasterPage的页面生命周期。介绍了页面事件触发顺序,特别是控件初始化与页面初始化之间的关系,并指出特殊情况下控件加载的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天碰到一个问题,在MasterPage的OnLoad中加入一个判断,希望在ContentPage的OnLoad之前执行,结果发现MasterPage的Onload在ContentPage的OnLoad后执行,后来把这个判断移动到MasterPage的OnInit中搞定

在一个单独的页面中,执行顺序为

  1. PreInit
  2. Init
  3. InitComplete
  4. PreLoad
  5. Load
  6. LoadComplete
  7. PreRender
  8. PreRenderComplete

在页面有MasterPage的时候

  1. ContentPage.PreInit
  2. Master.Init
  3. ContentPage.Init
  4. ContentPage.InitComplete
  5. ContentPage.PreLoad
  6. ContentPage.Load
  7. Master.Load
  8. ContentPage.LoadComplete
  9. ContentPage.PreRender
  10. Master.PreRender

注意上面高亮的部分,除此之外其他的地方一般是先MasterPage后ContentPage,这里恰恰相反

那么控件的加载和页面的几个事件的关系是什么呢?

一般情况下,页面中的控件回先于OnInit执行,亦即

  1.  Master中控件的Init
  2. ContentPage中控件的Init
  3. Master.Init
  4. Content.Init
  5. Content.Load
  6. Master.Load
  7. Master.中用户控件load
  8. ContentPage页面中的用户控件的 page_load

可以看到控件的Init在Page的Init前执行,所以在Init中我们就可以放心使用页面中的控件了,但是下面的情况不同

如果你的页面中使用WebControl,或者从WebControl继承的控件,WebControl需要使用CreateChildControls()来加载子控件,这个函数会在这个控件的Init后被调用,也就是说在一个WebControl的OnInit中,是没有办法直接使用其中的控件的,不过我们也可以自己用FindControl把控件加载进来,WebControl的其他方法的加载顺序见下表

EventDescription
InitYou can use the OnInit method to trap this event and initialize member variables and other values.
LoadViewStateYou can trap this event to customize how the control retrieves information from the ASP.NET hidden ViewState field.
LoadThis event is raised after you create and initialize the control. This is the best place to make the connection to the database or load document content. You can trap the Load event by adding the OnLoad method to the class.
PreRenderThis event is raised before ASP.NET renders the control. Any changes to the control's state are saved into the hidden ViewState field.
SaveViewStateThis event is raised before the control state is persisted into the hidden ViewState field. You can trap the event to customize how this information is stored.
RenderYou can use the Render method to respond to this event and specify the HTML code that represents the component's content.
DisposeThis event is useful for cleanup operations. It's raised before the control is torn down and is the best place to free the resources created during the load phase.
UnloadThis event is raised before the control is torn down. The official documentation says not to use this event to perform cleanup, and to rely on the Dispose event instead.
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值