方法對比表
| # | 方法 | 關鍵代碼 | 特點 |
| 1 | ClientScript.RegisterStartupScript | ClientScript.RegisterStartupScript(GetType(), "msg", "<script>alert('提示')</script>", true); | 無白屏,推薦用於普通頁面 |
| 2 | Response.Write 直接輸出 | Response.Write("<script>alert('提示')</script>"); | 有白屏(輸出在 HTML 結構前),不推薦 |
| 3 | 靜態工具方法封裝 | public static void Show(Page page, string msg) { page.ClientScript.RegisterStartupScript(page.GetType(), "msg", "<script>alert('" + msg + "')</script>", true); } | 復用性強,無白屏 |
| 4 | Response.Write (另一寫法) | Response.Write("<script>alert('提示')</script>"); | 同方法 2,有白屏 |
| 5 | showModalDialog (模態窗口) | window.showModalDialog('XXX.aspx', '', 'dialogWidth:400px;dialogHeight:200px;'); | IE 專屬,現代瀏覽器已棄用 |
| 6 | RegisterStartupScript 打開新窗口 | Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>window.open('url')</script>"); | 用於彈出新頁面 |
| 7 | ScriptManager.RegisterStartupScript (AJAX/UpdatePanel) | ScriptManager.RegisterStartupScript(this, GetType(), "key", "alert('提示')", true); | **部分更新面板內必須用此方法** |
| 8 | Literal/Label 控件輸出腳本 | litScript.Text = "<script>alert('提示')</script>"; (置於 body 底部) | 可控制輸出位置,需頁面預置控件 |
核心區別:ClientScript vs ScriptManager
- ClientScript:普通全頁回發,腳本在頁面加載時執行。
- ScriptManager:AJAX 異步回發(UpdatePanel 內),腳本在部分更新完成後執行。**UpdatePanel 內不能用 ClientScript**。
最佳實踐封裝類
public static class MessageBox
{
// 普通頁面
public static void Show(Page page, string message)
{
page.ClientScript.RegisterStartupScript(
page.GetType(), "alert",
"alert('" + message.Replace("'", "\\'") + "');", true);
}
// UpdatePanel 異步回發
public static void ShowAjax(Control control, string message)
{
ScriptManager.RegisterStartupScript(
control, control.GetType(), "alert",
"alert('" + message.Replace("'", "\\'") + "');", true);
}
// 確認框(返回值需異步處理)
public static void Confirm(Page page, string message, string callbackFunc)
{
page.ClientScript.RegisterStartupScript(
page.GetType(), "confirm",
"if(confirm('" + message.Replace("'", "\\'") + "')) { " + callbackFunc + "(); }", true);
}
}
現代化建議
- 前端使用美觀的模態框(SweetAlert2, Layer, Toastr)替代原生
alert。
- 後端返回 JSON,前端 AJAX 統一處理提示,解耦前後端。
- 避免
Response.Write 和 showModalDialog。