In ASP.NET 2.0 most controls have the AutoPostBack property so that you can do server side processing when the state of the control changes. This usually works great even with some JavaScript to confirm the change. However, I ran into a problem with the CheckBox. There isn’t a OnClientClick property like LinkButton’s have. Thus we must use the JavaScript onclick event to do our confirmation. The ASP.NET engine also uses this property to create the AutoPostBack JavaScript code. So it’s very important we don’t mess that up. See the C# code below. Our confirm only returns if the user clicked the cancel button, and then it returns a false. If the user clicks the ok button, it skips over the return and executes the ASP.NET doPostBack function.

<asp:CheckBox ID="CheckBoxDev" runat="server" Text="Developer" ToolTip="Developers have access to everything."
              AutoPostBack="True" OnCheckedChanged="CheckBoxDev_CheckedChanged"/>
const string DevConfirm = "if (!confirm('Confirm changing developer status.')) return false;";
CheckBoxDev.Attributes.Add("onclick", DevConfirm);

One Comment

  1. Thanks! That code is awesome! I tried the regular return confirm() and as you mention it messed up the autopostback of the checkbox. This is a nice hack to what should be a simple solution.


Post a Comment

*
*