btnDelete.Attributes["onclick"] = "return confirm('確定要刪除嗎?');";
string script = $@"
if (confirm('{EscapeJs(msg)}'))
window.location.href = '{yesUrl}';
else
window.location.href = '{noUrl}';";
Response.Write($"");
ClientScript.RegisterStartupScript(GetType(), "msg", $"alert({EscapeJs("刪除成功!")});", true);
ClientScript.RegisterStartupScript(GetType(), "msg",
$"alert({EscapeJs("刪除成功!")}); window.location.href='List.aspx';", true);
RegisterStartupScript:腳本置於頁面底部 </form> 前,DOM 已就緒,適合啟動邏輯。RegisterClientScriptBlock:腳本置於頁面頂部 <form> 後,適合函式定義、變數宣告。
public static class MessageBox
{
private static string JsEscape(string s)
=> s.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\n", "\\n").Replace("\r", "\\r");
public static void Alert(Page page, string msg)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "alert", $"alert('{JsEscape(msg)}');", true);
}
public static void AlertAndRedirect(Page page, string msg, string url)
{
string script = $"alert('{JsEscape(msg)}'); window.location.href='{url}';";
page.ClientScript.RegisterStartupScript(page.GetType(), "alertRedirect", script, true);
}
public static void Confirm(Button btn, string msg)
{
btn.Attributes["onclick"] = $"return confirm('{JsEscape(msg)}');";
}
public static void ShowModal(Page page, string url, int width, int height)
{
string features = $"width={width},height={height},resizable=yes,scrollbars=yes";
string script = $"window.open('{url}', 'modalWin', '{features}');";
page.ClientScript.RegisterStartupScript(page.GetType(), "modal", script, true);
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
// ... 儲存邏輯
MessageBox.AlertAndRedirect(this, "儲存成功!", "List.aspx");
}
protected void Page_Load(object sender, EventArgs e)
{
MessageBox.Confirm(btnDelete, "確定刪除此筆資料?");
}
Swal.fire({title:'確認', text:'刪除後無法復原', icon:'warning', showCancelButton:true}) 回傳 Promise。toastr.success('已儲存')。window.open 模態視窗,支援無障礙、響應式。fetch('/api/save', {method:'POST', body:formData}).then(r=>r.json()).then(data=>{ if(data.ok) toastr.success(data.msg); })。
private static string EscapeJs(string s)
{
return s.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"").Replace("\n", "\\n").Replace("\r", "\\r");
}
所有輸出至 JavaScript 字串的伺服器端變數,務必經過逸出,防止 XSS 與語法錯誤。