伺服器端註冊啟動腳本
// 1. 簡單彈窗
string url = "TargetPage.aspx";
ClientScript.RegisterStartupScript(GetType(), "openWin", $"window.open('{url}');", true);
// 2. 指定視窗屬性
string features = "resizable=1,scrollbars=0,status=1,menubar=no,toolbar=no,location=no";
ClientScript.RegisterStartupScript(GetType(), "openWin", $"window.open('{url}', '', '{features}');", true);
Response.Write 直接輸出 (舊式、不建議)
Response.Write($"");
導向與彈窗比較
| 方法 | 行為 | 原視窗 |
| Response.Redirect("B.aspx") | 伺服端 302 導向 | 被取代 |
| Server.Transfer("B.aspx") | 伺服端轉交 (URL 不變) | 被取代 |
| window.open('B.aspx') | 客戶端新視窗 | 保留 |
| window.showModalDialog('B.aspx') | 模態對話框 (IE 專屬、已淘汰) | 保留但凍結 |
| window.showModelessDialog('B.aspx') | 非模態對話框 (IE 專屬、已淘汰) | 保留 |
通用訊息框 Helper 類別
public static class MessageBox
{
public static void Show(Page page, string message)
{
string script = $"alert({JsonSerialize(message)});";
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "msg", script, true);
}
public static void ShowAndRedirect(Page page, string message, string url)
{
string script = $"alert({JsonSerialize(message)}); window.location.href='{url}';";
page.ClientScript.RegisterStartupScript(page.GetType(), "msgRedirect", script, true);
}
public static void Confirm(Button btn, string message)
{
btn.Attributes["onclick"] = $"return confirm({JsonSerialize(message)});";
}
// 簡易 JSON 字串逸出
private static string JsonSerialize(string s)
=> "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r") + "\"";
}
使用範例
protected void btnDelete_Click(object sender, EventArgs e)
{
// 執行刪除邏輯...
MessageBox.ShowAndRedirect(this, "刪除成功!", "List.aspx");
}
protected void Page_Load(object sender, EventArgs e)
{
MessageBox.Confirm(btnDelete, "確定要刪除嗎?");
}
現代最佳實務
- 前端使用 SweetAlert2、Toastr、Bootstrap Modal 替代原生
alert/confirm。
- 搭配 AJAX/Fetch 非同步呼叫,避免整頁重新載入。
- 伺服器端回傳 JSON 結果,前端依狀態碼顯示 Toast/Modal。