伺服器控件雖強大,但純伺服器端處理會導致頻繁回發、頁面閃爍、使用者體驗不佳。ASP.NET 提供完整的客戶端腳本註冊與管理機制 (ClientScriptManager),讓控件開發者能優雅地注入 JavaScript,實現無回發驗證、AJAX 互動、動態 UI 等現代 Web 體驗。
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes["onclick"] = "return validateForm();";
Button1.Attributes["onmouseover"] = "this.className='btn-hover';";
Button1.Attributes["data-tooltip"] = "點擊提交表單";
}
ClientScriptManager (ASP.NET 2.0+,取代 Page.RegisterClientScriptBlock 等舊方法) 位於 Page.ClientScript:
// 註冊腳本庫 (如 jQuery, 自訂 JS 檔)
// 參數:型別 (通常用 this.GetType())、金鑰、URL
Page.ClientScript.RegisterClientScriptInclude(
this.GetType(),
"jquery",
"https://code.jquery.com/jquery-3.6.0.min.js"
);
// 解析相對路徑 (WebResource.axd 嵌入資源)
Page.ClientScript.RegisterClientScriptInclude(
this.GetType(),
"MyControlScript",
Page.ClientScript.GetWebResourceUrl(this.GetType(), "MyControls.Scripts.mycontrol.js")
);
// 頁面頂部 (head 區域) - 適合函式定義、變數宣告
Page.ClientScript.RegisterClientScriptBlock(
this.GetType(),
"MyNamespace",
"var MyApp = { config: { debug: true } };",
true // addScriptTags: 自動包裹