views:

50

answers:

2

Here's what I want to do. I want the users to be able to delete their own posts but I want them to confirm this first, so when the user clicks the Delete link, I want to display a confirmation dialog with Yes and No (the standard Javascript confirmation dialog), if the user chooses 'No' nothing happens and the page won't post back but if they choose 'Yes' the page should post back to the server, how can this be done with Javascript in ASP.NET?

Thanks

Edit: Thanks a lot guys, I guess I'll go for OnClientClick="return confirm("Are you sure?");"

+2  A: 

You need to (in your code behind):

  1. Use the ClientScript object to get the postback reference for your button as a string
  2. Modify the OnClientClick property of the button to include the followign javascript and the previously retrieved reference:

    btn.OnClientClick = "return confirm('are you sure?');" + btnPostbackReferenceString;

  3. Profit.

ck
Thanks for the answer, but what do I need btnPostbackReferenceString for?
Waleed Eissa
So that your button still fires the event it would have fired before you change the click handler.
ck
+1 for "Profit!" ;-)
Cerebrus
The last step should always be to profit....
ck
+1  A: 

add your confirmation to your button like that :

submitButton.Attributes["onclick"] = 
  "if (!confirm('Do you want to continue ?')){return false;}";

if user selects no, confirm returns false, then your code returns false and the postback will be avoided.

Note that : if you return confirm('some text'), your postback will be avoided whatever user selects.

Canavar
oh, but why is that? I tried to use OnClientClick="return confirm('Are you sure?');" and it worked fine in IE6 and FF3, does it cause problems with some browsers?
Waleed Eissa
Besides I checked the page source and didn't see ASP.NET adding anything to onclick
Waleed Eissa
I'm not so sure about if (true) return true...?
ck