5

I working on an ASP.Net C# application, I wanted to create a Button Control, when user click on the button, a JavaScript confirm popup, then get the Boolean value from the user (Yes/No) to perform further actions in the button onClick event.

my current approach was added OnClientClick and OnClick event in the button, where OnClientClick trigger JavaScript function and the (Yes/No) value is store into HiddenField Control to make use during OnClick event.

It is something like the following code fragments:

function CreatePopup(){
            var value = confirm("Do you confirm?");
            var hdn1 = document.getElementById('hdn1');
            hdn1.Value = value;
        }

<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick="CreatePopup()"/>
<asp:HiddenField ID="hdn1" runat="server" />

Is there any better approach in order to do this? thank you in advanced.

2
  • do you need to fire up a server event even if user say "no"? Commented Oct 25, 2011 at 10:01
  • Yes that is the requirement, see the comment to my answer! Commented Oct 25, 2011 at 10:11

2 Answers 2

12

Change your CreatePopup() function to return a boolean:

function CreatePopup()
{
    return confirm("Do you confirm?");
}

And then ensure you return that from the OnClientClick() in the button:

<asp:Button ... OnClientClick="return CreatePopup();" />

Using that method, the OnClick() method will only fire if the OnClientClick() method returns true.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your comment, I need to fire the OnClick() event all the time, so the solution above cannot apply in my situation :)
Why not just have two ASP buttons for the user instead of deferring their decision to the JS confirm? Then you can put yes/no specific code in the handlers and call a common method for the rest. If your solution works though and you're happy with it I see no reason to change it!
0

Why do you want to store the value of the JavaScript confirmation in the hidden field? Just simply return false in your JavaScript function when the confirm value is 'no' , to prevent the form from submitting. When cnfirm value is yes, return true to allow the form to be submitted. In your code behind in the button_click method you don't have to check what happened in your JavaScript confirm, since form will never be submitted if the user said no.

1 Comment

I wanted the Yes / No value everytime when user click on the Button, mean I always wanted OnClick() event to fire and need the Yes / No value, just why I stored it in hiddenfield

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.