Reputation: 3896
I have an asp:button
called "Delete" and what I want to do is have a JavaScript confirm popup with the options "Yes" and "No". If "Yes" then delete a record from a SQL DB else if "No" then nothing should happen.
<asp:Button runat="server" ID="btnDelete" Text="Delete"
OnClientClick="if(confirm('Delete?'))alert('You chose yes!');else alert('You chose no!')"
OnClick="btnDelete_Click" />
btnDelete_Click
contains SQL delete logic.
The problem I am having is that the OnClick
method always gets executed. Whether you pick "Yes" or "No" from the JavaScript popup the record gets deleted regardless. It seems to always cause a postback.
Can I somehow get the "Yes" or "No" result into my code behind so I can actually do a simple "if" statement for the delete logic?
Upvotes: 0
Views: 10783
Reputation: 74
Try with this
<asp:Button runat="server" ID="btnDelete" Text="Delete" OnClientClick="if(confirm('Delete?')){return true;}else {return false;} OnClick="btnDelete_Click" />
When you are using OnClientClick event with JS confirm dialog box at that time you need to return true or false. If it will return True then OnClick(Server side) event will fire otherwise it will not.
Upvotes: 0
Reputation: 196
You should ideally put JS event handlers in the script tag, and call them from your OnClientClick event in the button definition. Like so:
<script type="text/javascript">
function ConfirmDelete() {
return confirm("Delete?");
}
</script>
And then in your button's OnClientClick event, you do this:
OnClientClick="return ConfirmDelete()"
This keeps your markup clean and readable, and will also prevent the postback from happening if the user chooses 'No'.
Upvotes: 0
Reputation: 1967
Try this, on your javascript do this
var result = Confirm("Are you sure . . . . ");
if(result)
return true;
else
return false;
what it does is if it's true, it should postback your code, else it'd cancel your click.
Upvotes: 5
Reputation: 1631
That should be:
<asp:Button runat="server" ID="btnDeleteSite" Text="Delete" OnClientClick="return confirm('Format Delete?');" OnClick="btnDeleteSite_Click" />
Upvotes: 0