我在Asp.net应用程序中有一个GridView控件,它有<asp:buttonField> type="image"CommandName="Delete"

有没有办法在到达OnRowDelete事件之前执行一段javascript?

我想在删除行之前进行简单的确认。

谢谢!

编辑:请注意<asp:ButtonField>标记没有 OnClientClick属性。

有帮助吗?

解决方案

我会使用TemplateField,并使用常规的asp:Button或asp:ImageButton填充ItemTemplate,具体取决于所需的内容。然后,您可以执行与拦截Delete命令时RowCommand事件要执行的逻辑相同的操作。

在其中任何一个按钮上,我将使用OnClientClick属性在此之前执行JavaScript确认对话框。

<script type="text/javascript">
   function confirmDelete()
   {
       return confirm("Are you sure you want to delete this?");
   }
</script>

...

<asp:TemplateField>
  <ItemTemplate>
     <asp:ImageButton ID="DeleteButton" runat="server"
        ImageUrl="..." AlternateText="Delete" ToolTip="Delete"
        CommandName="Delete" CommandArgument='<%# Eval("ID") %>'
        OnClientClick="return confirmDelete();" />
  </ItemTemplate>
</asp:TemplateField>

其他提示

我发现最优雅的方法是使用jQuery连接onClick事件:

<script type="text/javascript"> 
    $(".deleteLink").click(function() {
      return confirm('Are you sure you wish to delete this record?');
    });
</script>

...

<asp:ButtonField ButtonType="Link" Text="Delete"
    CommandName="Delete" ItemStyle-CssClass="deleteLink" />

请注意,我使用任意CSS类来标识链接按钮。

GridViewRowCreated事件处理程序中,使用FindControl查找命名按钮,并添加到Attributes集合中:

btn.Attributes.Add("onclick", "return confirm('delete this record?');");

只有在confirm()为真时才会执行ASP.Net代码,即已经确定。

所以我有一个javascript函数:

function confirmDeleteContact() {
  if (confirm("Are you sure you want to delete this contact?")) {
    document.all.answer.value="yes";
  } else {
    document.all.answer.value="no";
  }
}

我将它连接到网格项,如下所示:

Sub dgbind(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles dgcontacts.ItemDataBound
    Select Case e.Item.ItemType
        Case ListItemType.Item, ListItemType.AlternatingItem
            CType(e.Item.Cells(9).Controls(0), System.Web.UI.WebControls.LinkButton).Attributes.Add("onclick", "javascript:confirmDeleteContact();")
    End Select
End Sub

这是一些旧代码,所以我看到一些我可以改变的东西,但道德是:如果所有其他方法都失败了,添加javascript <!>“onClick <!>”;在行绑定期间。 QUOT <!>; <!> document.all.answer.value QUOT;是一个隐藏字段,有runat=server,以便我可以在回发时读取值。

如果您使用buttonfield,则更好地添加引用System.Windows.Forms ...它始终可用于所有.net框架并支持asp.net ..

如果按钮区域是您的最佳选择,这是您的选择.. 样品:

using System.Windows.Forms;

protected void BorrowItem_RowCommand(object sender, GridViewCommandEventArgs e)
{

    if (e.CommandName == "Delete")
    {

        if (System.Windows.Forms.MessageBox.Show("Do you want to delete", "Delete",MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) != System.Windows.Forms.DialogResult.OK)
        {
            return;
         }
     }
//Continue execution...
}

//drimaster
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top