ASP.NET WebForms 時代,伺服端控件渲染為 HTML,常需在後台動態註冊 JavaScript、綁定客戶端事件、控制控件行為。本文彙整實戰常用模式,雖屬舊技術,但維護專案時仍具參考價值。
// 頁面載入後執行 (舊 API,含 Script 標籤)
ClientScript.RegisterStartupScript(GetType(), "alertKey", "alert('頁面載入完成');", true);
// 頁面載入後執行 (新 API,不含 Script 標籤,適合 UpdatePanel)
ScriptManager.RegisterStartupScript(this, GetType(), "alertKey", "alert('AJAX 後執行');", true);
// 註冊外部 JS 檔案
ClientScript.RegisterClientScriptInclude("jquery", "/Scripts/jquery.min.js");
// TextBox 失去焦點驗證
txtEmail.Attributes["onblur"] = "validateEmail(this);";
// DropDownList 選項變更觸發
ddlCategory.Attributes["onchange"] = "loadSubCategories(this.value);";
// 唯讀/禁用切換
txtCode.Attributes["readonly"] = "readonly";
txtCode.Attributes.Remove("readonly"); // 移除唯讀
// 樣式動態控制
divPanel.Attributes["style"] = "display:none;"; // 隱藏
divPanel.Attributes["class"] = "alert alert-warning";
function validateRequired(fieldId, msg) {
var val = document.getElementById(fieldId).value.trim();
if (!val) { alert(msg); return false; }
return true;
}
// 使用:按鈕 OnClientClick
function toggleTextBox(chkId, txtId) {
var chk = document.getElementById(chkId);
var txt = document.getElementById(txtId);
txt.disabled = !chk.checked;
txt.readOnly = !chk.checked;
if (chk.checked) txt.focus();
}
// 前台綁定
// 嵌入式程式碼區塊 (僅 .aspx/.ascx 可用)
var clientId = '<%= txtName.ClientID %>';
// 後台程式碼傳遞給 JS 變數
ScriptManager.RegisterStartupScript(this, GetType(), "ids",
$"var txtNameId = '{txtName.ClientID}';", true);
// ASP.NET 4.0+ ClientIDMode="Static" (ID 不變)
// 頁面初始載入 + 非同步回發後皆執行
function pageLoad() {
// 重新綁定 jQuery 事件、插件初始化
$('.datepicker').datepicker();
bindCustomEvents();
}
// 或使用 Sys.Application.add_load
Sys.Application.add_load(function() {
// ...
});
WebForms 後台註冊 JS 核心 API:`ClientScript.RegisterStartupScript`、`ScriptManager.RegisterStartupScript`、`Control.Attributes`。掌握 `ClientID` 處理、`OnClientClick` 攔截、`UpdatePanel` 部分更新重綁,即可應對多數舊專案維護需求。**新代碼請勿模仿此模式,擁抱前後端分離架構。**