Reputation: 3896
I need to add an "are you sure" popup window to a delete button and I am not sure how to get whether the user clicked Ok or Cancel.
Here is how I do it:
string message = "Are you sure you want to delete this user?";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("return confirm('");
sb.Append(message);
sb.Append("');");
Type type = this.GetType();
ClientScript.RegisterOnSubmitStatement(type, "alert", sb.ToString());
Upvotes: 1
Views: 18715
Reputation: 1104
I agree with above answers, but in case you don't wanna mix you server and client side code/events then I would suggest you go with AjaxToolKit confirm button http://bit.ly/NtmpOT
Upvotes: 0
Reputation: 2104
If you are using ajax control toolkit just use the confirmextender
if you want to know wich button the user clicked try this
add a hidden field in your webform
and use this to set his value when the user click Ok
sb.Append("if (confirm(").Append(msg).Append("))")
.Append("document.getElementById('")
.Append(confirmResult.ClientID)
.Append("').value = 'ok';");
in your code behind read the value of confirmResult to know if the user clicked ok or cancel
Upvotes: 1
Reputation: 13672
You could just set OnClientClick on the button to:
return confirm("Are you sure you want to delete this user?");
Then the submit/postback won't happen if the user doesn't click OK.
Upvotes: 5
Reputation: 3213
The simplest way is to just add this to your <input type="button|submit|reset" />
or <button />
html markup (no submit on cancel): OnClick="if(!confirm('Are you sure?')) return false;"
Rename the event to OnClientClick
for <asp:Button />
- it is compatible with CausesValidation="True"
and/or UseSubmitBehavior="False"
, because it gets added before them in the html markup.
Upvotes: 2