ASP:Checkbox how to autopostback only on checked?

David Hague picture David Hague · Jan 7, 2010 · Viewed 12.8k times · Source

I've got a checkbox that's set up as below:

<asp:CheckBox ID="myCheckbox" runat="Server" OnClick="showLoadingScreen(this.checked);" AutoPostBack="true" Text="Check me for more data!" /> 

The function showLoadingScreen is as below:

function showLoadingScreen(isChecked) {         
if (isChecked)
    {
        document.getElementById('form1').style.display='none';
        document.getElementById('img_loading').style.display='block';
    }
else { return false; }
}

I've added the else clause in hopes that I can get it to only post back when the checkbox is checked, but it's posting back in either case.

I've got a grid on the page (inside form1) that has a set of data loaded into it on page load, but in order to add some extra data to it I've added this checkbox (its a longer running process, so I only want to load it on demand, not upfront). When it's checked I want to show the loading gif, postback, grab the data, and return. If the box gets unchecked I don't want to do anything, since leaving more than enough data on the page is perfectly fine (that is to say, the data displayed upfront is a subset of the data displayed when the checkbox is checked).

Is there any way to make it so the checkbox auto posts back on checked, but not on unchecked?

Edit: Using Dark Falcon's suggestion, I've modified the checkbox to look like:

<asp:CheckBox ID="myCheckbox" runat="Server" OnClick="return showLoadingScreen(this.checked);" AutoPostBack="true" Text="Include HQ Values" /> 

And the javascript to be:

function showLoadingScreen(checked) {         
alert(checked);
if (checked)
    {
        document.getElementById('form1').style.display='none';
        document.getElementById('img_loading').style.display='block';
        document.form1.submit();  //my own addition, to get it to post back
    }
else { return false; }
}

Now, it posts back on checked, but the box is not able to be unchecked anymore. As you can see I've added an alert to show the value being passed in. It's passing in the correct value when you uncheck the box (false), but then it somehow gets checked again.

It's not a huge issue, since there's really no reason to ever uncheck the box (since as I stated before, the dataset when checked is a superset of the unchecked dataset), but I'd still like to know why it's doing that. Any ideas?

Answer

Bryan picture Bryan · Jan 7, 2010

Do not set AutoPostBack in this case. "AutoPostBack" means post back to the server any time the value of this control changes... which is NOT what you want.

Instead, use GetPostBackEventReference(myCheckbox,"") to get the appropriate postback script and call this from your showLoadingScreen method if the checkbox is checked.