首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

ASP.NET 動態控制 Page Head 信息最佳實踐:Literal + PlaceHolder 替代 Response.Write 與 JS 方案

     編輯:MySQL 資料庫相關知識

背景痛點

  • 傳統 Response.Write 破壞代碼與 UI 分離原則。
  • <title runat="server" id="titleControl"> 產生多餘 id 屬性。
  • JS 動態設置 Title 對搜索引擎不友好(SEO 隱患)。

推薦架構:BasePage 封裝

在基類 BasePage 中封裝 Head 控制邏輯,所有 WebForm 繼承 BasePage 即可複用。

核心控件選型

需求控件理由
動態設置 Title、Meta(Description/Keywords)Literal直接輸出文本,不產生多餘標籤/屬性,乾淨利落
動態載入 CSS/JSPlaceHolder佔位符,便於動態添加 HtmlGenericControl 子控件

關鍵代碼片段

1. 通用 Head 設置方法

private void SetHeader(string controlId, string text) {
    Literal lit = this.FindControl(controlId) as Literal;
    if (lit != null) lit.Text = text;
}

2. 設置 Title 封裝

protected void SetTitle(string title) {
    SetHeader("PageTitle", "<title>" + title + "</title>");  // 頁面需預置 <asp:Literal ID="PageTitle" runat="server" />
}

WebForm 中調用:this.SetTitle("呂的部落格");

3. 動態載入 CSS/JS

private Control FindHeader() {
    return this.FindControl("LoadHeader");  // 頁面預置 <asp:PlaceHolder ID="LoadHeader" runat="server" />
}

protected void LoadPlaceHolder(HtmlGenericControl ctrl) {
    Control ph = FindHeader();
    if (ph != null) ph.Controls.Add(ctrl);
}

protected void LoadCss(string path) {
    var link = new HtmlGenericControl("link");
    link.Attributes["rel"] = "stylesheet";
    link.Attributes["type"] = "text/css";
    link.Attributes["href"] = path;
    link.Attributes["media"] = "screen";
    LoadPlaceHolder(link);
}

protected void LoadJs(string path) {
    var script = new HtmlGenericControl("script");
    script.Attributes["type"] = "text/javascript";
    script.Attributes["src"] = path;
    LoadPlaceHolder(script);
}

WebForm 中調用:this.LoadCss("~/Styles/site.css"); / this.LoadJs("~/Scripts/common.js");

優勢總結

  • 編譯時類型安全,智能提示友好。
  • 輸出純淨 HTML,無多餘 id、name 屬性。
  • SEO 友好:Title/Meta 為服務端直輸,搜索引擎可直接抓取。
  • 統一維護:BasePage 集中管理,佈局頁/內容頁皆可調用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved