Response.Write 破壞代碼與 UI 分離原則。<title runat="server" id="titleControl"> 產生多餘 id 屬性。在基類 BasePage 中封裝 Head 控制邏輯,所有 WebForm 繼承 BasePage 即可複用。
| 需求 | 控件 | 理由 |
|---|---|---|
| 動態設置 Title、Meta(Description/Keywords) | Literal | 直接輸出文本,不產生多餘標籤/屬性,乾淨利落 |
| 動態載入 CSS/JS | PlaceHolder | 佔位符,便於動態添加 HtmlGenericControl 子控件 |
private void SetHeader(string controlId, string text) {
Literal lit = this.FindControl(controlId) as Literal;
if (lit != null) lit.Text = text;
}
protected void SetTitle(string title) {
SetHeader("PageTitle", "<title>" + title + "</title>"); // 頁面需預置 <asp:Literal ID="PageTitle" runat="server" />
}
WebForm 中調用:this.SetTitle("呂的部落格");
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");
id、name 屬性。