依主題、語系、裝置、A/B 測試動態切換樣式表,需在伺服端程式化建立 `` 標籤並加入 `
`。本文示範標準 `HtmlLink` 控制項用法、主題切換完整範例、以及避免重複註冊與快取策略。protected void RegisterStylesheet(string url, string key = null) {
if (Page.Header == null) return;
key = key ?? url;
// 簡易去重:檢查是否已存在相同 href
bool exists = Page.Header.Controls
.OfType()
.Any(l => l.Href.Equals(ResolveClientUrl(url), StringComparison.OrdinalIgnoreCase));
if (exists) return;
var link = new HtmlLink {
Href = ResolveClientUrl(url),
Attributes = { ["rel"] = "stylesheet", ["type"] = "text/css" }
};
Page.Header.Controls.Add(link);
}
public enum UiTheme { Light, Dark, HighContrast }
private static readonly Dictionary ThemeCssMap = new() {
[UiTheme.Light] = "~/Content/themes/light.css",
[UiTheme.Dark] = "~/Content/themes/dark.css",
[UiTheme.HighContrast] = "~/Content/themes/high-contrast.css"
};
public class BasePage : System.Web.UI.Page {
protected UiTheme CurrentTheme {
get => (UiTheme)(ViewState["Theme"] ?? UiTheme.Light);
set => ViewState["Theme"] = value;
}
protected override void OnPreInit(EventArgs e) {
base.OnPreInit(e);
// 移除舊主題
var oldLinks = Header.Controls.OfType().Where(l => l.Attributes["rel"] == "stylesheet" && ThemeCssMap.Values.Contains(l.Href)).ToList();
foreach (var l in oldLinks) Header.Controls.Remove(l);
// 加入新主題
RegisterStylesheet(ThemeCssMap[CurrentTheme], "theme");
}
protected void RegisterStylesheet(string url, string key) { /* 同前文 */ }
}
protected void btnSwitchTheme_Click(object sender, EventArgs e) {
CurrentTheme = (UiTheme)(((int)CurrentTheme + 1) % Enum.GetValues(typeof(UiTheme)).Length);
// 若使用 UpdatePanel,需觸發 Header 更新,建議全頁 Postback 或將 Theme CSS 改用 由 JS 切換
}
private static readonly HashSet _registeredCssKeys = new HashSet();
public static void RegisterCssOnce(Page page, string url, string key) {
if (page.Header == null) return;
if (!_registeredCssKeys.Add(key)) return; // 進程級去重 (跨請求也生效,視需求調整)
var link = new HtmlLink {
Href = page.ResolveClientUrl(url),
Attributes = { ["rel"] = "stylesheet", ["type"] = "text/css" }
};
page.Header.Controls.AddAt(0, link); // 插在最前,優先級較高
}
新專案 (特別是 SPA、Blazor、React) 建議採用建置時期 CSS 方案,避免執行期動態註冊的複雜度。若維護傳統 WebForms,上述 `HtmlLink` 模式仍為最標準、相容性最佳的做法。