在gridview中javascript确认后未触发Onclick asp.net事件

Onclick asp.net event not triggered after javascript confirmation in gridview

本文关键字:Onclick asp net 事件 gridview javascript 确认      更新时间:2023-09-26

在我的网格视图中,我将一个javascript OnClick方法与一个要求确认删除有界行的链接buton关联:

protected void DeleteRow_Click(object sender, EventArgs e)
    {
        GridViewRow grdrow = (GridViewRow)((LinkButton)sender).NamingContainer;
        using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
        {
            string cartId = usersShoppingCart.GetCartId();
            int rowIndex = grdrow.RowIndex;
            //int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
            string itemId = ((HiddenField)CartList.Rows[rowIndex].FindControl("hiddenEncryptedItemID")).Value;
            usersShoppingCart.RemoveItemWithOptionsAndValues(cartId, itemId);
            CartList.DataBind();
            lblTotal.Text = String.Format("{0:N2}", usersShoppingCart.GetTotal());
            //return usersShoppingCart.GetCartItems();
        }
    }

出于美观的原因,我以这种方式构建了我的ItemTemplate:

<ItemTemplate>
   <div class="divItemTotal">
       <div>
           <asp:Label runat="server" CssClass="totalItem" ID="lblItemTotalPrice" Text='<%#: String.Format("{0:N2}", ((Convert.ToDouble(Item.Quantity)) *  Convert.ToDouble(Item.UnitPrice)))%>'></asp:Label>
            <asp:Label runat="server" ID="lblCurrency2" Text=" €"></asp:Label></div>
            <asp:LinkButton OnClick="DeleteRow_Click" CssClass="removeItem imgRemoveItem" runat="server" ID="DeleteRow"></asp:LinkButton>
       </div>

在一个完美的世界里,javascript方法应该阻止页面执行回发,并在确认后让它离开。不幸的是,当单击"确定"时,没有发生任何事情,ASP.net方法也从未被触发。更奇怪的是,有了javascript函数,asp方法只会不时地启动,我对此仍然没有任何假设。

试试这个

<ItemTemplate>
  <div class="divItemTotal">
   <div>
      <asp:Label runat="server" CssClass="totalItem" ID="lblItemTotalPrice" Text='<%#: String.Format("{0:N2}", ((Convert.ToDouble(Item.Quantity)) *  Convert.ToDouble(Item.UnitPrice)))%>'></asp:Label>
      <asp:Label runat="server" ID="lblCurrency2" Text=" €"></asp:Label></div>
      <asp:LinkButton CommandArgument='<%# Eval("Item.Id") %>' CommandName="Delete" CssClass="removeItem imgRemoveItem" runat="server" ID="DeleteRow"></asp:LinkButton>
   </div> 

代码隐藏:

protected void CartList_RowDataBound(object sender, GridViewRowEventArgs e)
{ 
LinkButton l = (LinkButton)e.Row.FindControl("DeleteRow"); 
l.Attributes.Add("onclick", "javascript:return " +
"confirm('Are you sure you want to delete this record " +
DataBinder.Eval(e.Row.DataItem, "Item.Id") + "')");
}

protected void GridView1_RowCommand(object sender, 
                     GridViewCommandEventArgs e)
{
 if (e.CommandName == "Delete")
 {
   // get the categoryID of the clicked row
  int categoryID = Convert.ToInt32(e.CommandArgument);
  // Delete the record 
  DeleteRecordByID(categoryID);
// Implement this on your own :) 
}
}