Asp.net2.0頁面執行順序

來源:互聯網
上載者:User

今天碰到一個問題,在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的其他方法的載入順序見下表


Event Description
Init You can use the OnInit method to trap this event
and initialize member variables and other values.
LoadViewState You can trap this event to customize how the
control retrieves information from the ASP.NET hidden ViewState field.
Load This 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.
PreRender This event is raised before ASP.NET renders the
control. Any changes to the control's state are saved into the hidden ViewState
field.
SaveViewState This 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.
Render You can use the Render method to respond to this
event and specify the HTML code that represents the component's
content.
Dispose This 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.
Unload This 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.
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.