ASP.NET CheckBox does not fire CheckedChanged event when unchecking

前端 未结 9 694
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 10:04

I have a CheckBox on an ASP.NET Content Form like so:



        
相关标签:
9条回答
  • 2020-12-08 10:57

    I wanted to tidy things up a bit so I've just spent a bit of time testing a solution for this.

    joshb is correct with his explanation for why the CheckBox behaves the way it does.

    As I don't know how I got round this last year or even if I did (I can't remember what I was working on at the time to check), I've put together a simple solution/workaround.

    public class CheckBox2 : CheckBox
    {
        protected override bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            bool isEventTarget = postCollection["__EVENTTARGET"] == UniqueID;
            bool hasChanged = base.LoadPostData(postDataKey, postCollection);
            hasChanged = hasChanged || isEventTarget;
            return hasChanged;
        }
    }
    

    If you now register CheckBox2 in your page and use it in place of your standard CheckBoxes, you will get the CheckedChanged event fired as you expect with ViewState disabled and AutoPostBack enabled.

    The way this works is allowing the normal CheckBox to do its thing with validation and change checking, but then performs an additional check to see if it was the target of the event that caused the postback. If it was the target, it returns true to tell the framework to raise the CheckedChanged event.

    Edit: Please note that this only solves the problem for AutoPostBack on the CheckBox. If the PostBack is invoked from anything else (a button, for example), the CheckedChanged event still exhibits the observed problem.

    0 讨论(0)
  • 2020-12-08 11:02

    To fire CheckedChanged event set the following properties for CheckBox, AutoPostBack property should be true and should have a default value either checked false or true.

    AutoPostBack="true" Checked="false"
    
    0 讨论(0)
  • 2020-12-08 11:06

    It's an old post but I had to share my simple solution in order to help others who searched for this problem.

    The solution is simple: Turn on AutoPostBack.

            <asp:CheckBox id="checkbox1" runat="server"
                    AutoPostBack="True" //<<<<------
                    Text="checkbox"
                    OnCheckedChanged="knowJobCBOX_CheckedChanged"/>
    
    0 讨论(0)
提交回复
热议问题