萬盛學電腦網

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

ASP.NET GridView 刪除前確認對話框實作 (JavaScript + TemplateField)

最簡單做法:RowDataBound 註冊客戶端確認

protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataControlRowType.DataRow) return;

    // 找到刪除按鈕 (CommandName="Delete" 的 Button/LinkButton/ImageButton)
    var btnDelete = e.Row.Cells[0].Controls.OfType

進階:使用 TemplateField 完整控制按鈕樣式與參數

<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
    OnRowCommand="gvData_RowCommand" OnRowDataBound="gvData_RowDataBound">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="名稱" />
        <asp:TemplateField HeaderText="操作">
            <ItemTemplate>
                <asp:LinkButton ID="btnEdit" runat="server" CommandName="Edit" CommandArgument='<%# Eval("Id") %>'>編輯</asp:LinkButton>
                <asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" CommandArgument='<%# Eval("Id") %>'
                    OnClientClick='return confirm("確定刪除 \'<%# Eval("Name") %>\' 嗎?");'>刪除</asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

後端刪除邏輯

protected void gvData_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        int id = Convert.ToInt32(e.CommandArgument);
        // 執行刪除 (參數化 SQL / EF Core)
        using (var ctx = new MyDbContext())
        {
            var entity = ctx.Items.Find(id);
            if (entity != null) { ctx.Items.Remove(entity); ctx.SaveChanges(); }
        }
        BindGridView(); // 重新繫結
    }
}

現代化替代:Bootstrap Modal / SweetAlert2

<!-- 引入 SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<asp:LinkButton ID="btnDelete" runat="server" CommandName="Delete" CommandArgument='<%# Eval("Id") %>'
    OnClientClick='return Swal.fire({title:"確定刪除?",text:"此操作無法復原",icon:"warning",showCancelButton:true,confirmButtonText:"刪除",cancelButtonText:"取消"}).then(r=>r.isConfirmed);'>
    刪除</asp:LinkButton>

無刪除按鈕時的替代方案:AutoGenerateDeleteButton

// 僅啟用自動產生刪除欄
gvData.AutoGenerateDeleteButton = true;

// RowDataBound 中統一加上確認
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var btn = e.Row.Cells[0].Controls[0] as LinkButton; // 第一欄第一個控制項
        if (btn != null && btn.CommandName == "Delete")
            btn.OnClientClick = "return confirm('確定刪除?');";
    }
}

注意事項

  • UpdatePanel 內:`OnClientClick` 正常運作,但 `confirm` 會阻擋非同步 PostBack,需確認 `ScriptManager` 正確註冊。
  • CommandArgument 注入:`Eval("Id")` 直接輸出至 HTML 屬性,確保資料來源可信,或使用 `HttpUtility.HtmlAttributeEncode`。
  • CSRF 防護:刪除等寫入操作務必驗證 AntiForgeryToken (MVC) 或 ViewStateUserKey (Web Forms)。
copyright © 萬盛學電腦網 all rights reserved