ASP.NET 2.0 引入 <head runat="server">,使 <title> 成為伺服器端可控制的 HtmlHead 控制項。透過 Page.Title 或 Page.Header.Title 即可動態設定。
// Page_Load 或任何事件中
protected void Page_Load(object sender, EventArgs e)
{
// 方式 1:直接屬性 (推薦)
Page.Title = $"目前時間:{DateTime.Now:yyyy-MM-dd HH:mm}";
// 方式 2:透過 Header 控制項
// Page.Header.Title = "另一種寫法";
}
當使用 SiteMapPath, Menu, TreeView 等導航控制項時,SiteMap.CurrentNode 會自動對應目前頁面節點。遞迴向上蒐集祖先節點標題,組成「首頁 :: 產品 :: 手機 :: iPhone 15」格式。
using System;
using System.Web;
using System.Web.UI;
public partial class BasePage : Page
{
private const string DefaultTitle = "歡迎光臨本站";
private const string UnnamedTitle = "Untitled Page";
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
SetDynamicTitle();
}
private void SetDynamicTitle()
{
// 若頁面已在 .aspx 靜態設定 Title,或為預設未命名,則自動覆蓋
if (string.IsNullOrEmpty(Title) || Title == UnnamedTitle)
{
if (SiteMap.CurrentNode == null)
{
Title = DefaultTitle;
}
else
{
Title = BuildTitleFromSiteMap(SiteMap.CurrentNode);
}
}
}
///
/// 迴圈向上建立階層標題 (效能優於遞迴)
///
private string BuildTitleFromSiteMap(SiteMapNode currentNode)
{
var parts = new System.Collections.Generic.List();
var node = currentNode;
while (node != null)
{
if (!string.IsNullOrEmpty(node.Title))
parts.Insert(0, node.Title); // 插入頭部,保持根->葉順序
node = node.ParentNode;
}
return string.Join(" :: ", parts);
}
///
/// 遞迴版本 (教學參考)
///
private string BuildTitleRecursive(SiteMapNode node)
{
if (node.ParentNode == null) return node.Title ?? "";
return BuildTitleRecursive(node.ParentNode) + " :: " + (node.Title ?? "");
}
}
// _Layout.cshtml
@ViewData["Title"] - 我的網站
// Controller
public IActionResult Detail(int id)
{
var product = _service.Get(id);
ViewData["Title"] = $"{product.Category} :: {product.Name}";
return View(product);
}
// Razor Page (PageModel)
public void OnGet(int id)
{
Product = _service.Get(id);
ViewData["Title"] = $"{Product.Category} :: {Product.Name}";
}
<title> 為 **最重要的 SEO 標籤**,前 60 字元最關鍵,請置放核心關鍵字。頁面具體標題 | 網站名稱 或 層級1 :: 層級2 :: 頁面標題。Page.Title = HttpUtility.HtmlEncode(userInput) + " - 搜尋結果";ASP.NET 2.0 的 runat="server" 讓標題動態化變得簡單;結合 SiteMap 可自動同步導航與標題,減少維護成本。現代架構改用 ViewData/ViewBag/模型綁定,核心邏輯不變:**單一來源產生標題,確保一致性與 SEO 優化**。