取消选中时,ASP.NET CheckBox不会启动CheckedChanged事件

我在ASP.NET内容表单上有一个CheckBox,如下所示:
<asp:CheckBox runat="server" ID="chkTest" AutopostBack="true" OnCheckedChanged="chkTest_CheckedChanged" />

在我的代码背后我有以下方法

protected void chkTest_CheckedChanged(object sender,EventArgs e)
{
}

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

当我再次单击复选框时,它将被取消选中,页面发回,但是没有调用chkTest_CheckedChanged。

该过程是可重复的,所以一旦CheckBox被取消选中,检查它将触发事件。

我在Web.Config中禁用了View State,启用View State会导致此问题消失。在View State仍然被禁用的情况下,我可以做什么可靠的事件触发?

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

更新2:
我已经覆盖了我的页面中的OnLoadComplete,从内部我可以确认Request.Form [“__ EVENTTARGET”]已正确设置为我的CheckBox的ID。

解决方法

实现一个自定义CheckBox存储在ControlState而不是ViewState中的Checked属性可能会解决这个问题,即使复选框有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);
            }
        }
    }
}

更多信息here

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...