Saturday, November 1, 2014

Checkbox does not change its checked value after postback

 have a checkbox from where I get the checked value but the first time works great but then I doesn't change at all after postback and always returns true.
I'm just doing this

bool accepted = this.chkAccepted.Checked;
My checkbox is inside a control. Not repeater not directly in a page.
<asp:CheckBox ID="chkAccepted" runat="server" Checked="true"/>Accepted

The first time it starts checked = true. I click my button first postback and work fine, then I uncheck, click my button but the checked is still true.
The first time it starts checked = true. I uncheck the checkbox and I click my button first postback and work fine, then I check, click my button but the checked is true, then I uncheck again and is always checked = true.
So, what is the bug for this?
I have another checkbox in the same control which has no Checked property initialized and always works fine. So how can I solve this problem please?



I realized that it's a .NET bug after some research. So when the property Checked of the checkbox is set to true in the aspx, this causes the problem. So, I removed this property and in the Page_Load event(server side) I initialized the checkboxes as true inside a Page.IsPostBack == false. And that's solved my problem.


solved

<asp:CheckBox ID="chkRem"  value="true" runat="server" Text="تذكرني"  />
  <asp:HiddenField ID="chkremHid" runat="server" />


<script>
   //check box for login
            $('#chkRem').change(function () {
                if ($('#chkRem').prop('checked'))
                    $('#chkremHid').val("True");
                else
                    $('#chkremHid').val("False");
            });

</script>



in code behind
use the hidden field value instead chekbox
c#
string check = chkremHid.Value;



No comments:

MS in Computer Science with paid training in USA company