• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2739
  • Last Modified:

Getting the value returned from a confirmation box using asp.net c#

I have this javascript within my aspx page and i want to
be able to determine my users response. if they click ok
on the confirmation message i want to run a set of C# code
and if they click cancel I dont want anything to happen.

How can i store the result of
btnExit.Attributes.Add("onclick", "return confirm_delete();");

below in a variable. I will like to determine that value of true
or false stored to determine which code to run.

I am using asp.net 2005 c#


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">      
        function confirm_delete()
            if (confirm("The checked file(s) will be deleted?")==true)
                  return true;
                  return false;
    <form id="form1" runat="server">
        <asp:Button ID="btnExit" runat="server" Height="53px" OnClick="Button1_Click" Text="Button"
            Width="198px" /></div>
protected void Button1_Click(object sender, EventArgs e)
        String result;
        btnExit.Attributes.Add("onclick", "return confirm_delete();");
	// if confirm_delete() = true
        // dosomething
	// else
	// do nothing

Open in new window

1 Solution
First of all, you need to put the code that adds the attribute into your Page_load sub so that the attribute is set when the page is sent to the client.  That enables the javascript to act when the button is pressed.

Second, confirm() will return true or false.  Then, the OnClick event for your C# code will only be called if  the Confirm() returns true.

This example uses the built-in java confirm function to pop up a confirmation window and wait for input
        btnExit.Attributes.Add("onclick", "javascript:if(confirm('Delete this record?')== false) return false;")
SirdotsAuthor Commented:
Thanks. I added the attribute code to my page load and it works well. Once I click ok it processes code within my click event and once I click cancel it doesnt do any thing which makes it good.

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now