iT邦幫忙

0

asp.net頁面與用戶控件之間的生命週期順序

https://ithelp.ithome.com.tw/upload/images/20200706/20125526KWSIQpPyEr.png

我對"如果最終在托管頁面的Page_PreRender事件處理程序(跟在Page_Load事件處理程序之後)中設置這些值,就能夠在控件的Page_Load的方法中訪問這些值"這段話有些疑惑,控件的Page_Load事件不是在頁面的Page_PreRender事件前就發生了,那為何在頁面的Page_PreRender事件發生後,還能在控件的Page_Load事件去取得值呢?

備註:圖片擷取自"ASP.NET 入门经典 基于Visual Studio 2015 第9版"這本書。

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2020-07-06 20:29:30
最佳解答

如果最終在托管頁面的Page_PreRender事件處理程序(跟在Page_Load事件處理程序之後)中設置這些值,就能夠在控件的Page_Load的方法中訪問這些值

我猜執行順序是這樣的
1.托管頁面的 Page_Load
2.托管頁面的 Page_PreRender
3.控件的 Page_Load
4.控件的 Page_PreRender

要驗證上面猜測是否正確
就在上面四個事件裡顯示一些不同的訊息
然後執行一下就知道執行順序了

我沒有 Visual Studio 2015
就不試了

dp27530 iT邦新手 5 級 ‧ 2020-07-06 21:11:56 檢舉

海綿寶寶大哥你好,我有嘗試過了,他的執行順序是:
[托管頁面的Page_Load->用戶控件的Page_Load->托管頁面的Page_PreRender->用戶控件的Page_PreRender]
所以這就是我對這句話的疑惑點,不過這本書是翻譯本,我在想會不會是翻譯錯了或是原文寫錯了?

我去找了原文
應該是翻譯錯了
應該不是「如果...就能夠...」而是「如果...就以為可以...你就會碰到未預期的...」

節錄原文如下

Thus, you would be able to set values in the Page_Load method of the hosting page and then access
those values in the control’s Page_Load method. However, if you ended up setting those values in
the hosting page’s Page_PreRender event handler (which comes after the Page_Load event handler),
yet expected to be able to access those values in the control’s Page_Load method, then you will get
unexpected behavior because those properties were not set as required. This can be mitigated by not
doing any work in your control until after Page_Load has been called.
dp27530 iT邦新手 5 級 ‧ 2020-07-06 21:27:44 檢舉

海綿寶寶大神有心了,感謝解惑!

我要發表回答

立即登入回答