Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript before asp:ButtonField click

I have a GridView control in an Asp.net application, that has a <asp:buttonField> of type="image" and CommandName="Delete".

Is there any way to execute a piece of javascript before reaching the OnRowDelete event?

I want just a simple confirm before deleting the row.

Thanks!

EDIT: Please Note that <asp:ButtonField> tag does not have an OnClientClick attribute.

like image 931
Pablo Fernandez Avatar asked Oct 20 '08 14:10

Pablo Fernandez


3 Answers

I would use a TemplateField instead, and populate the ItemTemplate with a regular asp:Button or asp:ImageButton, depending one what is needed. You can then execute the same logic that the RowCommand event was going to do when it intercepted the Delete command.

On either of those buttons I would then use the OnClientClick property to execute the JavaScript confirm dialog prior to this.

<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>
like image 192
steve_c Avatar answered Nov 13 '22 15:11

steve_c


I found that the most elegant way to do this is to use jQuery to wire the onClick event:

<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" />

Notice that I use an arbitrary CSS class to identify the link button.

like image 15
Tod Birdsall Avatar answered Nov 13 '22 17:11

Tod Birdsall


In the GridView's RowCreated event handler, use FindControl to find the named button, and add to the Attributes collection:

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

Your ASP.Net code will only be executed if confirm() is true, i.e. has been ok'd.

like image 3
devio Avatar answered Nov 13 '22 16:11

devio