Reputation: 83
How to stop the page from rendering the .cs
code on click of cancel button on javascript confirm box?
I have a button click event and in some IF
condition I am asking the user to confirm. Now when the user clicks on OK button, I have to bind the new data in a grid. but if the user clicks on cancel button, it should not refresh the grid with new data.
Question: On click of cancel button on JavaScript confirm box, how can I stop the following code to be executed, or how can I just return/break from JavaScript?
Can anyone please help me out with this? Thanks in advance.
Markup
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="false" OnClick="btnCopy_Click" ValidationGroup="Copy" />
Code
public void btnCopy_Click(object sender, EventArgs e) {
if (Convert.ToInt32(hidId.Value) > 0) {
string scriptString = "<script language='JavaScript'> ";
scriptString += "if (confirm('Are you sure to proceed?') == false) {return} ";
scriptString += "</script>";
Page.RegisterStartupScript("Confirm", scriptString);
BindDataGrid();
}
}
Upvotes: 6
Views: 13497
Reputation: 471
You are showing the confirm dialog in the codebehind of your button click, that wont stop the flow of your code.
You need to show the confirm dialogbox before do the postback
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="true" OnClientClick="return confirm('sure?');" ValidationGroup="Copy" />
Upvotes: 0
Reputation: 21117
You are mixing server and client side code in the same event, it has to be separated:
Script:
function Confirm()
{
var record=confirm('Are you sure to proceed??');
if(record == 1)
{
return true;
}
else if(record == 0)
{
return false;
}
}
Markup:
<asp:Button ID="btnCopy" runat="server" Text="Copy" Enabled="false"
OnClick="btnCopy_Click" OnClientClick='return Confirm();' ValidationGroup="Copy" />
Code-behind:
public void btnCopy_Click(object sender, EventArgs e) {
if (Convert.ToInt32(hidId.Value) > 0) {
BindDataGrid();
}
}
Upvotes: 7
Reputation: 999
You can simply return
from the code or exit(0)
.
function fillGrid()
{
if( confirm("....") )
{
//populate your grid
}
else
{
return;
}
//do anything after the grid is populated
//and exit the function
}
Upvotes: 0
Reputation: 1045
Please show the code, but without seeing your code I would guess you are not returning the response?
<input type="button" onclick=" return confirm('is this right?'); ">
Upvotes: 0
Reputation: 1355
You'll need to catch the response, for example:
if (window.confirm)
{
//handle the OK
}
else
{
//handle the cancel
}
Upvotes: 1