删除dataview的行之前确认删除

时间:2009-08-05 17:48:17

标签: asp.net javascript html

我有一个支持删除的GridView。我想添加一个弹出窗口,其中包含“您确定要删除此行吗?”之类的问题。

我的代码:

<asp:GridView id="GridAccounts" runat="server" AutoGenerateColumns="False" 
        ShowFooter="True" DataKeyNames="ID" 
        DataSourceID="AccountDataSource" onrowcommand="GridAccounts_RowCommand">
        <SelectedRowStyle BackColor="Lime" />
        <Columns>
            <asp:CommandField ButtonType="Image" ShowDeleteButton="True" DeleteImageUrl="~/Pictures/delete.jpg" />
            <asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
                <EditItemTemplate>
                    <asp:Label ID="LabelAccountIDUpdate" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Button ID="ButtonAccountIDInsert" runat="server" CommandName="Insert" Text="Insert" />
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="LabelAccountID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

代码背后:

protected void GridPaymentMethod_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton deleteButton = (ImageButton)e.Row.Cells[0].Controls[0];
            MyMoney.PaymentMethodRow row = (MyMoney.PaymentMethodRow)((System.Data.DataRowView)e.Row.DataItem).Row;
            deleteButton.OnClientClick = string.Format("return confirm('Are you sure you want to delete payment method {0}?');", row.Name.Replace("'", @"\'"));
        }
    }

这呈现为:

<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="return confirm('Are you sure you want to delete payment method Gotovina?');javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />

如果我在确认窗口中单击“确定”,则会发生回发,但没有任何反应。如果我注释掉RowDataBound代码,那么删除工作正常。代码无需确认弹出:

<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />

我做错了什么?

3 个答案:

答案 0 :(得分:3)

我相信this就是你要做的事情的一个例子。它更干净,你不必使用后面的代码。

答案 1 :(得分:1)

在您的代码中,您必须将ButtonType =“Image”更改为ButtonType =“Link” - 然后onclick =“...”将在没有javascript:___ doPostBack(...)部分的情况下呈现。并且在GridPaymentMethod_RowDataBound事件中设置类似deleteButton.Text =“&lt; img src = \”path_to_image \“... /&gt;” (使用html实体而不是&lt;&gt;)。

或者你可以在ASP.NET AjaxToolkit套件中使用带有ComamndName =“delete”和ConfirmButtonExtender的ImageButton。

答案 2 :(得分:0)

deleteButton.OnClientClick = string.Format("((!confirm('Are you sure you want to delete payment method {0}?'))?return false);", row.Name.Replace("'", @"\'"));