取消选中时,ASP.NET CheckBox不会触发CheckedChanged事件

Mat*_*att 27 asp.net viewstate

我在ASP.NET内容表单上有一个CheckBox,如下所示:

<asp:CheckBox runat="server" ID="chkTest" AutoPostBack="true" OnCheckedChanged="chkTest_CheckedChanged" />
Run Code Online (Sandbox Code Playgroud)

在我的代码后面我有以下方法:

protected void chkTest_CheckedChanged(object sender, EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)

当我在浏览器中加载页面并单击CheckBox时,它会被检查,页面会回发,我可以看到chkTest_CheckedChanged被调用.

然后,当我再次单击CheckBox时,它将取消选中,页面会回发,但chkTest_CheckedChanged不会被调用.

该过程是可重复的,因此一旦取消选中CheckBox,检查它将触发事件.

我在Web.Config中禁用了View State,启用View State会导致此问题消失.在View State保持禁用状态时,我可以做些什么才能获得可靠的事件?

更新: 如果我Checked="true"在服务器标签上设置,当取消选中CheckBox时事件触发,情况就会反转,而不是相反.

更新2: 我已经OnLoadComplete在我的页面中覆盖了,并且从那里我可以确认Request.Form["__EVENTTARGET"]已正确设置我的CheckBox的ID.

Abl*_*ias 26

要触发CheckedChanged事件,请为CheckBox设置以下属性,AutoPostBack属性应为true,并且应该具有false或true的默认值.

AutoPostBack="true" Checked="false"
Run Code Online (Sandbox Code Playgroud)

  • 对于这个简单的问题,公认的答案是太过分了。这个答案应该是公认的答案。 (3认同)

Joh*_*ny5 19

实现一个存储Checked属性的自定义CheckBox,ControlState而不是ViewState可能解决该问题,即使复选框有AutoPostBack=false

与ViewState不同,ControlState不能被禁用,并且可用于存储对控件行为至关重要的数据.

我现在没有可视化工作室环境进行测试,但这应该是这样的:

public class MyCheckBox : CheckBox
{
    private bool _checked;

    public override bool Checked { get { return _checked; } set { _checked = value; } }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        //You must tell the page that you use ControlState.
        Page.RegisterRequiresControlState(this);
    }

    protected override object SaveControlState()
    {
        //You save the base's control state, and add your property.
        object obj = base.SaveControlState();

        return new Pair (obj, _checked);
    }

    protected override void LoadControlState(object state)
    {
        if (state != null)
        {
            //Take the property back.
            Pair p = state as Pair;
            if (p != null)
            {
                base.LoadControlState(p.First);
                _checked = (bool)p.Second;
            }
            else
            {
                base.LoadControlState(state);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息在这里.


jos*_*shb 8

它不会触发,因为在禁用viewstate的情况下,服务器代码不知道先前已选中该复选框,因此它不知道状态已更改.至于asp.net知道复选框控件在回发之前未经检查,仍未选中.这也解释了您在设置时看到的反向行为Checked="true".


小智 7

这是一个老帖子,但我必须分享我的简单解决方案,以帮助其他搜索此问题的人.

解决方案很简单:打开AutoPostBack.

        <asp:CheckBox id="checkbox1" runat="server"
                AutoPostBack="True" //<<<<------
                Text="checkbox"
                OnCheckedChanged="knowJobCBOX_CheckedChanged"/>
Run Code Online (Sandbox Code Playgroud)


Cri*_*eta 6

我不确定,但我猜我的解决方案仅适用于.NET Framework 4.0:

使用ViewStateMode = "Disabled"禁用视图状态insted的的EnableViewState="false".除了您可以保存本地视图状态之外,这将警告相同的行为.

因此,在您的复选框上,设置属性ViewStateMode = "Enabled"并解决问题,而不实施自定义复选框.