How to use Sweet Alert in ASP.NET C#

10,159

OnClientClick waits bool result to invoke server event but Confirm methods return nothing. ( function (isConfirm) returns async.)

You could call server event on function (isConfirm) manually like

<script type="text/javascript">
    function Confirm(ctl, event) {
        event.preventDefault();
        swal({
            title: "Confirm Logout?",
            text: "Do you really want to log this Account out?",
            type: "warning",
            showCancelButton: true,
            closeOnConfirm: true,
            closeOnCancel: true
        },
        function (isConfirm) {
            if (isConfirm) {
               _doPostBack('btnLogout', 'OnClick');
            } 
        });

       return false;
    }
</script>
Share:
10,159
Boooo Booooo
Author by

Boooo Booooo

By Day: Software Engineer By Night: Brother For Fun: Memes "Give me a place to stand and I will move the earth" -Archimedes

Updated on June 05, 2022

Comments

  • Boooo Booooo
    Boooo Booooo almost 2 years

    I am trying to use the sweet alert to use as a pop-up message in my ASP.NET C# application. But I think I am doing wrong because, If I click the button or Link button, nothing really happens. it's just like an element without an event.

    So here is the code.

    JAVASCRIPT

    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
        <script type="text/javascript">
            function Confirm(ctl, event) {
                event.preventDefault();
                swal({
                    title: "Confirm Logout?",
                    text: "Do you really want to log this Account out?",
                    type: "warning",
                    showCancelButton: true,
                    closeOnConfirm: true,
                    closeOnCancel: true
                },
                function (isConfirm) {
                    if (isConfirm) {
                        return true;
                    } else {
                        return false;
                    }
                });
            }
        </script>
    

    ASPX

        <li class="nav-item">
      <asp:LinkButton ID="btnLogout" CssClass="nav-link" runat="server" OnClick="btnLogout_Click" OnClientClick="return Confirm(this,event)"><i class="icon ion-android-exit"></i></asp:LinkButton></li>
    

    C#

     protected void btnLogout_Click(object sender, EventArgs e)
        {
             Session.Abandon();
             Response.Redirect("login.aspx");
        }