首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

強型別參考母版頁子控件

     編輯:關於ASP.NET

避免 FindControl 反射效能損耗:母版頁暴露公共靜態屬性

問題:FindControl 效能差

this.Master.FindControl("SideBarBox") as ContentPlaceHolder

每次呼叫皆透過反射搜尋控件樹,高流量下極度耗效能。

解決方案:母版頁 Page_Init 公開強型別參考

// MasterPage.master.cs
public static ContentPlaceHolder sideBarBox;

protected void Page_Init(object sender, EventArgs e)
{
    sideBarBox = SideBarBox; // 指派實例參考
}

關鍵:頁面生命週期順序

  1. 母版頁控件 Init
  2. 內容控件 Init
  3. 母版頁 Init ← **此處指派,確保子頁 Page_Load 前完成**
  4. 內容頁 Init
  5. 內容頁 Load
  6. 母版頁 Load
  7. ...

若在母版頁 Page_Load 指派,子頁 Page_Load 讀取時尚為 null。

子頁使用

public partial class ErrorPage : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        FE_Error.InitErrorPage(ErrorBox, MasterPage.sideBarBox); // 直接強型別存取
    }
}

進階:巢狀 ContentPlaceHolder

母版頁中 ContentPlaceHolder 可巢狀,同樣可暴露內層參考,靈活佈局。

此模式將母版頁視為強型別服務提供者,消除字串鍵值與反射,大幅提升效能與可維護性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved