[javascript] Confirm postback OnClientClick button ASP.NET

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
                           OnClick="BtnUserDelete_Click"
                           OnClientClick="return UserDeleteConfirmation();" 
 meta:resourcekey="BtnUserDeleteResource1" />

I have tried:

function UserDeleteConfirmation() {
        if (confirm("Are you sure you want to delete this user?"))
            return true;
        else
            return false;
}

and

function UserDeleteConfirmation() {
    if (confirm("Are you sure you want to delete this user?")) {
            __doPostBack(btnUserDelete, '');
    }

    return false;
 }

And none of them works.

This question is related to javascript asp.net button postback

The answer is


I know this is old and there are so many answers, some are really convoluted, can be quick and inline:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" OnClick="BtnUserDelete_Click" OnClientClick="return confirm('Are you sure you want to delete this user?');" meta:resourcekey="BtnUserDeleteResource1" />
                       

This is a simple way to do client-side validation BEFORE the confirmation. It makes use of the built in ASP.NET validation javascript.

<script type="text/javascript">
    function validateAndConfirm() {
        Page_ClientValidate("GroupName");  //'GroupName' is the ValidationGroup
        if (Page_IsValid) {
            return confirm("Are you sure?");
        }
        return false;
    }
</script>

<asp:TextBox ID="IntegerTextBox" runat="server" Width="100px" MaxLength="6" />
<asp:RequiredFieldValidator ID="reqIntegerTextBox" runat="server" ErrorMessage="Required"
    ValidationGroup="GroupName"  ControlToValidate="IntegerTextBox" />
<asp:RangeValidator ID="rangeTextBox" runat="server" ErrorMessage="Invalid"
    ValidationGroup="GroupName" Type="Integer" ControlToValidate="IntegerTextBox" />
<asp:Button ID="SubmitButton" runat="server" Text="Submit"  ValidationGroup="GroupName"
    OnClick="SubmitButton_OnClick" OnClientClick="return validateAndConfirm();" />

Source: Client Side Validation using ASP.Net Validator Controls from Javascript


try this :

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" 
   onClientClick=" return confirm('Are you sure you want to delete this user?')" 
   OnClick="BtnUserDelete_Click"  meta:resourcekey="BtnUserDeleteResource1"  />

try this : OnClientClick="return confirm('Are you sure ?');" Also set : CausesValidation="False"


Try this:

function Confirm() {
    var confirm_value = document.createElement("INPUT");
    confirm_value.type = "hidden";
    confirm_value.name = "confirm_value";

        if (confirm("Your asking")) {
            confirm_value.value = "Yes";
            document.forms[0].appendChild(confirm_value);
        }
    else {
        confirm_value.value = "No";
        document.forms[0].appendChild(confirm_value);
    }
}

In Button call function:

<asp:Button ID="btnReprocessar" runat="server" Text="Reprocessar" Height="20px" OnClick="btnReprocessar_Click" OnClientClick="Confirm()"/>

In class .cs call method:

        protected void btnReprocessar_Click(object sender, EventArgs e)
    {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == "Yes")
        {

        }
    }

The code is like this:

In Aspx:

<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CausesValidation=true />

in Cs:

protected void Page_Load(object sender, System.EventArgs e)
{
     if (!IsPostBack)
     {
         btnSave.Attributes["Onclick"] = "return confirm('Do you really want to save?')";          
     }
}

protected void btnSave_Click(object sender, EventArgs e){
    Page.Validate();
    if (Page.IsValid)
    {
       //Update the database
         lblMessage.Text = "Saved Successfully";
    }
}

Using jQuery UI dialog:

SCRIPT:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
 $(function () {

            $("#<%=btnUserDelete.ClientID%>").on("click", function (event) {
                event.preventDefault();
                $("#dialog-confirm").dialog({
                    resizable: false,
                    height: 140,
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                            __doPostBack($('#<%= btnUserDelete.ClientID %>').attr('name'), '');
                        },
                        Cancel: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            });
 });
</script>

HTML:

<div id="dialog-confirm" style="display: none;" title="Confirm Delete">
    <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure you want to delete this user?</p>
</div>

You can put the above answers into one line like this. And you don't need to write the function.

    <asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton"
         OnClick="BtnUserDelete_Click" meta:resourcekey="BtnUserDeleteResource1"
OnClientClick="if ( !confirm('Are you sure you want to delete this user?')) return false;"  />

Try this:

<asp:Button runat="server" ID="btnDelete" Text="Delete"
   onClientClick="javascript:return confirm('Are you sure you want to delete this user?');" OnClick="BtnDelete_Click" />

There are solutions here that will work, but I don't see anyone explaining what is actually happening here, so even though this is 2 years old I'll explain it.

There is nothing "wrong" with the onclientclick javascript you are adding. The problem is that asp.net is adding it's on onclick stuff to run AFTER whatever code you put in there runs.

So for example this ASPX:

<asp:Button ID="btnDeny" runat="server" CommandName="Deny" Text="Mark 'Denied'" OnClientClick="return confirm('Are you sure?');" />

is turned into this HTML when rendered:

<input name="rgApplicants$ctl00$ctl02$ctl00$btnDeny" id="rgApplicants_ctl00_ctl02_ctl00_btnDeny" 
onclick="return confirm('Are you sure?');__doPostBack('rgApplicants$ctl00$ctl02$ctl00$btnDeny','')" type="button" value="Mark 'Denied'" abp="547">

If you look closely, the __doPostBack stuff will never be reached, because the "confirm" will always return true/false before __doPostBack is reached.

This is why you need to have the confirm only return false and not return when the value is true. Technically, it doesn't matter if it returns true or false, any return in this instance would have the effect of preventing the __doPostBack from being called, but for convention I would leave it so that it returns false when false and does nothing for true.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to postback

Confirm postback OnClientClick button ASP.NET A potentially dangerous Request.Form value was detected from the client Forcing a postback Retrieving data from a POST method in ASP.NET How to use __doPostBack() OnclientClick and OnClick is not working at the same time? ASP.NET postback with JavaScript jQuery UI Dialog with ASP.NET button postback Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'