I have a problem with checkbox. For example, I have this aspx’s code
<asp:Content ID="MainContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:CheckBox ID="chkActive" AutoPostBack="True" OnCheckedChanged="Active_OnCheckedChanged" runat="server"></asp:CheckBox>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</asp:Content>
At server side, when chkActive is checked, I have two rendered controls:
- ctl00$MainContent$chkActive
- ctl00$MainContent$txtName
when chkActive is unchecked, I have only one rendered control:
- ctl00$MainContent$txtName
So I cannot write the status of that checkbox to database. For the record, I use a SaveData function with dynamic object, and chkActive disappeared when unchecked, so this function couldn’t find it. Any idea to make checkbox appeared even when it’s unchecked? Thanks.
P.S: “disappeared” means it’s not in Request.Form anymore when unchecked.
Edited:
My SaveData function:
public void SaveDate<T>(T entity, NameValueCollection attributes)
{
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo property in properties)
{
if (attributes.AllKeys.Any(key => key.Contains("$" + property.Name)))
{
//
}
}
}
The para attributes is from Request.Form, since checkbox is not in Request.Form anymore, so I don’t know how to handle it. This function works well in case checkbox is checked
As others have mentioned, the value of the checkbox (unchecked) is not sent back to the server, so it will not appear in the
Request.Formcollection.But… in your function, use can use the server-side objects because the value IS posted back in ViewState (provided you have it on).
this.chkActive.Checkedshould be false on postback when unchecked on the client and submitted.If you still want to use
Request.Form, you can always check to see if the entry exists in the collection. If it is not there, the checkbox was false, or unchecked.EDIT
To make the checkbox appear in the
Request.Formcollection, simply add a hidden input to your form and give it the same name as the checkbox.Add a client-side event handler to the OnClick event of the checkbox. When checked, set the hidden input’s disabled property to true. When unchecked, set the disabled property to false. Disabled controls are not sent back to the server just like unchecked checkboxes, so if the checkbox is checked, the input should be disabled, and visa-versa.