简体   繁体   English

ASP.Net复选框确认消息不起作用

[英]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 以下是我的chkSMTLock的 HTML代码

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

Here is my javascript: 这是我的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. 当我删除复选框的javascript事件绑定时,它将成功执行ServerSide事件。 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. 当您拥有AutoPostBack = true时,基本上就是在单击复选框时提交了一个表单,您的验证希望在表单级别进行。

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. 然后在ConfirmSMTLock()中检查复选框的状态,以查看是否需要触发确认对话框。 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. 由于AutoPostBack = true,它将自动将帖子发送回服务器。 So, first you need to delete that attribute from the html code. 因此,首先您需要从html代码中删除该属性。

<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. 然后,使用ASP.Net的__doPostBack函数实现PostBack行为。

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!!! 打开芝麻!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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