user125108
user125108

Reputation: 41

How to to confirming before deleting in ASP.NET?

I have code like this in Page_Load()

btnMainDelete.Attributes.Add("onclick", "if(confirm('Are you sure you want to delete this?')){}else{return true}");

Basically, it's confirming that before deletion (Yes/No). If it's a yes then delete the record and if it's no then do nothing.

For the btnMainDelete, I put as follow:

<asp:Button ID="btnMainDelete" runat="server" Text="Delete" OnClick="btnMainDelete_Click" />

Now the issue is that, what I press Yes or No always executes btnMainDelete_Click on the server side? I must have something missing here.

Thanks

Upvotes: 4

Views: 9982

Answers (5)

anishMarokey
anishMarokey

Reputation: 11397

you want to modify your code with

<asp:Button ID="btnMainDelete" runat="server" Text="Delete" OnClientClick  ="javascript:confirm('Are you sure want to delete ?');" />

OnClientClick : Gets or sets the client-side script that executes when a Button control's Click event is raised.

OnClick : Raises the Click event of the Button control

So in your case the confirm it should raise a client-side script. So you should give in a OnClientClick event .

Upvotes: 1

duc14s
duc14s

Reputation: 181

using this

btnDelete.Attributes.Add("onclick", "return confirm('Do you really want to delete this item?'

This will delete forever item in your database!');");

Upvotes: 0

rick schott
rick schott

Reputation: 21127

Put valid confirm script in the OnClientClick:

<asp:Button ID="btnMainDelete" OnClientClick="javascript:return confirm('Are you sure?');" runat="server" Text="Delete" OnClick="btnMainDelete_Click" />

Upvotes: 9

Scott
Scott

Reputation: 1228

Put your script in the OnClientClick

e.g.,

btnMainDelete.OnClientClick = "if (confirm('Are you sure you want to delete this?') == false) return false;";

Upvotes: 0

Quintin Robinson
Quintin Robinson

Reputation: 82355

You need to fix your script. In the script as written it is never preventing further execution of the script by returning false.

try:

return confirm('Are you sure you want to delete this?');

IE:

btnMainDelete.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this?');");

Upvotes: 7

Related Questions