萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 實用程式碼片段精選:開視窗、確認對話框、GridView 刪除與行點擊導航

片段集錦

1. 開啟新視窗並傳遞參數

父頁面 (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

2. 為按鈕加入確認對話框

// 簡單版
Button1.Attributes.Add("onclick", "return confirm('確定要執行此操作嗎?');");

// 完整邏輯版 (明確返回 true/false)
Button1.Attributes.Add("onclick", 
    "if(confirm('確定要刪除這筆資料嗎?')){ return true; } else { return false; }");

注意:`return confirm(...)` 直接回傳布林值決定是否繼續 PostBack,最簡潔。

3. GridView 刪除指定行資料 (使用 DataKeys)

<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 傳遞。

4. GridView 刪除前彈出確認 (範本欄位)

<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="lnkDelete" runat="server" CommandName="Delete" Text="刪除"
            OnClientClick="return confirm('確定刪除此筆資料?');" />
    </ItemTemplate>
</asp:TemplateField>

圖片示意:刪除確認對話框

5. GridView 行點擊導航至詳情頁

<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='';";
    }
}

圖片示意:行點擊導航效果

現代化改良建議

  • **確認對話框**:改用 Bootstrap Modal、SweetAlert2 等美觀替代原生 `confirm()`。
  • **GridView 替代**:新專案建議使用繁雜前端框架 (Vue/React/Angular) + Web API,或 ASP.NET Core Razor Pages + Tag Helpers / Blazor。
  • **參數化查詢**:所有 SQL 操作務必使用參數,防止注入。
  • **非同步**:資料存取改用 `async/await` 配合 `ExecuteNonQueryAsync` 提升延展性。

總結

這些片段涵蓋了 Web Forms 時代最常見的互動需求:跨頁傳值、使用者確認、資料刪除與行級導航。雖然技術棧逐漸演進,但「DataKeys 綁定主鍵」、「OnClientClick 回傳布林控制 PostBack」、「RowDataBound 動態註冊客戶端屬性」等核心模式,在理解 ASP.NET Web Forms 請求生命週期與控制項模型時仍具高度教學價值。

copyright © 萬盛學電腦網 all rights reserved