How do I cancel a submit event, caused by the press of a ButtonColumn
I am using an ASP datagrid, and I have a ButtonColumn. When the button is rendered to the page, it is a input of type submit. So its a submit button. The button is used for deleting records. But I want to have some javascript that confirms that the user wants to delete the record. The problem that I have is that even if I return false from the confirm method, the submit event still happens...
Here is the Server Side Code that assigns the javascript method to the click event:
Button deleteButton = e.Item.Cells[6].Controls[0] as Button;
if (deleteButton != null)
{
deleteButton.OnClientClick = "confirmDelete()";
}
Here is the ASP.net code that creates the datagrid:
<asp:DataGrid
runat="server"
ID="UsersList"
OnItemCommand="UsersList_ItemCommand"
AutoGenerateColumns="false"
HeaderStyle-CssClass="dataTableHeader"
Width="60%">
<Columns>
<asp:HyperLinkColumn DataNavigateUrlField="Username" DataTextField="Username" HeaderText="Username" DataNavigateUrlFormatString="~/Account/EditUser.aspx?user={0}"/>
<asp:BoundColumn DataField="Email" HeaderText="Email" />
<asp:ButtonColumn Text="Delete" HeaderText="Delete" ButtonType="PushButton" CommandName="DeleteUser" CausesValidation="false" />
</Columns>
</asp:DataGrid>
Here is the Javscript code that confirms the delete:
<script>
function confirmDelete() {
var x = confirm("This action cannot be undone. Are you sure you want to delete this user?");
return x;
开发者_开发问答 }
</script>
Perhaps there is no way to accomplish this with a ButtonColumn. I'm considering changing to a TemplateColumn, and just putting a button in there. But then I will have to redesign the code that handles these click events on the back end, which is currently handled in the ItemCommand handler.
Try:
deleteButton.OnClientClick = "return confirmDelete()";
You need to confirm delete on form.submit(), not deletebutton.click(), but you'll need to either assign an anonymous validation function to form.submit by the deletebutton.click(), or set a delete flag on deletebutton click, then check that value on form.submit(). That way other buttons that you WANT to submit the form still submit. And don't forget to clear the variable/or anon function after validation fails.
Replace the onclick listener on the button with an onsubmit listener on the form that returns false if you don't want to submit the form, something like:
<form onsubmit="return confirmDelete();" ...>
If confirmDelete returns false, the submit is cancelled. If it returns any other value, the form is submitted.
精彩评论