父頁面 (Server-side):
// 組合帶參數的 URL 並輸出 JavaScript 開啟新視窗
string url = $"Detail.aspx?id={id}&name={Server.UrlEncode(name)}";
string script = $"window.open('{url}', '_blank', 'width=800,height=600,resizable=yes');";
ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", script, true);
子頁面接收:
string id = Request.QueryString["id"];
string name = Request.QueryString["name"]; // 自動 UrlDecode
// 簡單版
Button1.Attributes.Add("onclick", "return confirm('確定要執行此操作嗎?');");
// 完整邏輯版 (明確返回 true/false)
Button1.Attributes.Add("onclick",
"if(confirm('確定要刪除這筆資料嗎?')){ return true; } else { return false; }");
注意:`return confirm(...)` 直接回傳布林值決定是否繼續 PostBack,最簡潔。
<asp:GridView ID="MyDataGrid" runat="server" DataKeyNames="emp_id" OnRowDeleting="MyDataGrid_RowDeleting">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
protected void MyDataGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int empID = (int)MyDataGrid.DataKeys[e.RowIndex].Value;
string deleteCmd = "DELETE FROM Employee WHERE emp_id = @id";
using (var conn = new SqlConnection(connStr))
using (var cmd = new SqlCommand(deleteCmd, conn))
{
cmd.Parameters.AddWithValue("@id", empID);
conn.Open();
cmd.ExecuteNonQuery();
}
BindGrid(); // 重新繫結
}
關鍵:設定 `DataKeyNames="emp_id"`,在 `RowDeleting` 事件中透過 `e.RowIndex` 取得 Key 值,避免隱藏欄位或 Session 傳遞。
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" Text="刪除"
OnClientClick="return confirm('確定刪除此筆資料?');" />
</ItemTemplate>
</asp:TemplateField>
圖片示意:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// 整行游標變手型
e.Row.Style["cursor"] = "pointer";
// 雙擊或單擊導航 (這裡示範單擊)
e.Row.Attributes["onclick"] = $"location.href='Detail.aspx?id={DataBinder.Eval(e.Row.DataItem, "id")}'";
// 可選:滑鼠進入/離開變色
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='#E0E0E0';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='';";
}
}
圖片示意:
這些片段涵蓋了 Web Forms 時代最常見的互動需求:跨頁傳值、使用者確認、資料刪除與行級導航。雖然技術棧逐漸演進,但「DataKeys 綁定主鍵」、「OnClientClick 回傳布林控制 PostBack」、「RowDataBound 動態註冊客戶端屬性」等核心模式,在理解 ASP.NET Web Forms 請求生命週期與控制項模型時仍具高度教學價值。