简体   繁体   中英

ASP.NET confirm dialog not working the second time

I have a form where I have a dropdownlist and many labels. When I select an option from dropdownlist it fetched data from database related to that option and populates them to field. Then I have a delete button. When I click on this that particular selected field from list will be deleted from database. For this before deleting whenever I click on delete button it ask for popup confirm dialog and when I click OK it will delete. I am using the below code for this.

JavaScript

<script type = "text/javascript">
    function Confirm() {
        if (Page_ClientValidate()) {
            var confirm_value = document.createElement("INPUT");
            confirm_value.type = "hidden";
            confirm_value.name = "confirm_value";
            if (confirm("You really want to delete the data?")) {
                confirm_value.value = "Yes";
            } else {
                confirm_value.value = "No";
            }
            document.forms[0].appendChild(confirm_value);
        }
    }
</script>

C#

protected void button_delete_Click(object sender, EventArgs e)
{
    string confirmValue = Request.Form["confirm_value"];
    if (confirmValue == "Yes")
    {
        // delete data from database
    }
}

ASP.NET

<asp:Button ID="button_delete" Visible="false" Text="Delete" runat="server" OnClientClick="Confirm()" OnClick="button_delete_Click" />

Initially the delete button is set to visible=false and only after selecting an item from list it becomes visible. Does this affect the confirm dialog after postback or something? It is working the first time and after I reload the page manually and try it works. But when I do it continuously without reloading page it wont work the second time. What is the issue here?

Change the Confirm to return a true or false value depending on the condition.

function Confirm() {

    var isFormValid = Page_ClientValidate();
    var isConfirmedByUser = confirm("You really want to delete the data?");

    //returns true when form is valid and user confirms action
    return (isFormValid  && isConfirmedByUser);               
}

and change the OnClientClick to

<asp:Button ID="button_delete" Visible="true" Text="Delete" runat="server" OnClientClick="return Confirm();" OnClick="button_delete_Click" />

when the Confirm() return a false value to OnClientClick it should not do a postback.

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