在伺服器端按鈕點擊事件中使用 Response.Write 註冊 alert 腳本,導致頁面 CSS 版面錯位、樣式失效。
Response.Write("<script language=javascript>");
Response.Write("window.alert('計劃添加失敗!');");
Response.Write("</script>");
Response.Write 直接輸出到回應流最前端,破壞頁面的 HTML 結構(特別是在 <!DOCTYPE> 之前)。ClientScript.RegisterStartupScript(
GetType(),
"alertScript",
"window.alert('計劃添加失敗!');",
true // 自動加上 script 標籤
);
public static void ShowAlert(Page page, string message)
{
string script = $"window.alert('{message.Replace("'", "\\'")}');";
ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", script, true);
}
UpdatePanel 非同步回傳時使用 ScriptManager.RegisterStartupScript。嚴禁在伺服器端使用 Response.Write 輸出腳本,統一改用 ClientScript 或 ScriptManager 註冊啟動腳本,確保頁面結構完整、樣式正常。