简体   繁体   中英

JavaScript Confirm on ASP.Net Button Control

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM