简体   繁体   中英

ASP.Net Checkbox Confirm Message not working

I have got a checkbox and want to display the confirmation message when it is clicked

I added the event binding in Code Behind file as below.

chkSMTLock.Attributes.Add("onclick", "return ConfirmSMTLock();");

The following is my HTML code for chkSMTLock

<asp:CheckBox ID="chkSMTLock" runat="server" AutoPostBack="true" OnCheckedChanged="chkSMTLock_CheckedChanged" Text="SMT Lock" />

Here is my javascript:

function ConfirmSMTLock() {
        var r = confirm('Are you sure that you want to SMT lock/unlock this account?');

        console.log(r);
        return r;
    }

When I run it, I can see the confirmation values (true/ false) in the browser console logs, but, it's not calling any server side code.

My server side code is very simple with logging...

protected void chkSMTLock_CheckedChanged(object sender, EventArgs e)
    {
        Utils.Debug("chkSMTLock_CheckedChanged");
    }

When I remove javascript event binding for the checkbox, it executes the ServerSide event successfully. But When I put it back, it stops working.

How can I use the confirmation message box to control it?

Your validation is too far down the chain. As you've got AutoPostBack=true, you're basically submitting a form when clicking the checkbox, your validation wants to be at the form level.

Form.Attributes.Add("onclick", "return ConfirmSMTLock();");

And in ConfirmSMTLock() check the status of the checkbox to see if you need to fire the confirm dialogue. That's the simplest way I can think of.

On a side note: if you do this:

chkSMTLock.Attributes.Add("onclick", "return false;");

The checkbox becomes untickable

I have found out an answer. Since AutoPostBack = true, it will automatically send a post back to the server. So, first you need to delete that attribute from the html code.

<asp:CheckBox ID="chkSMTLock" runat="server" OnCheckedChanged="chkSMTLock_CheckedChanged" Text="SMT Lock" />

Then implement the PostBack behaviour by using the __doPostBack function of ASP.Net.

function ConfirmSMTLock() {
        var r = confirm('Are you sure that you want to SMT lock/unlock this account?');

        if (r == true)
        {
            __doPostBack("chkSMTLock", '');            
            return true;
        }
        return false;
    }

Open Sasame!!!

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