ASP.Net Checkbox value at postback is wrong? ASP.Net Checkbox value at postback is wrong? asp.net asp.net

ASP.Net Checkbox value at postback is wrong?


This is a known problem with ASP.NET - for some reason ASP.NET won't update a checkbox on postback if it was disabled during page load and not checked for postback. I don't know exactly why that is though - if you make the checkbox unselected by default and select it, the value is changed on the server correctly.

The workaround is to add a hidden field to the page that represents the state of the checkbox, then update the field's value to "ON" or "OFF" for example, whenever the checkbox is clicked.

Then on the server you check the value of the hidden field, not the checkbox itself, as the hidden field is always posted.


I had a similar problem to this where the Checked property of the CheckBox object was not being updated correctly, to get the actual posted value you can check:

Request.Form[CheckBox1.UniqueID]

it will be 'on' if the box is checked and null if not.


Since you're already using Javascript to manipulate the controls state in the browser, I suggest you just disable the checkbox on the page load event in stead. Then your postbacks will work just fine...

<head>  <script type="text/javascript">    function buttonClick() {      var cb = document.getElementById('<%= CheckBox1.ClientID %>');      cb.disabled = false;      cb.parentNode.disabled = false;    }      </script></head><body onload="document.getElementById('<%= CheckBox1.ClientID %>').disabled = true;">  <form id="form1" runat="server">  <div>    <asp:checkbox id="CheckBox1" runat="server" checked="true" />    <asp:button id="Button1" runat="server" text="Button" onclientclick="buttonClick(); return false;" />    <asp:button id="Button2" runat="server" text="Button2" onclick="button2Click" />  </div>  </form></body>