I just got done fixing an issue that I was having with the ASP.NET AJAX Timer control, and I figured I’d write about it because there doesn’t seem to be like a ton of documentation out there right now as to exactly what is going on.

Here is the scenario: You have an Ajax enabled .aspx page which has an UpdatePanel set to update itself based upon a timed interval from a Timer control. You also have some type of submit button on the page that does a synchronous page submission. So, what happens when you click on the submit button, and before the page submit has run through it’s logic, the timer control trips and causes an asynchronous Ajax post? Well, what I was seeing was that the page would end up in an incongruous state – the submit works, but the page updates itself to show the results of the asynchronous update, not of the synchronous submit action.

This behavior is to be expected, to tell the truth. One of the actions has to win, and it may as well be the last one into the queue instead of the first. So, the real thing we want to do is disable the timer control based upon the submit button being clicked. No problem, I thought – I’ll just disable it in the event handler for the button click, like this:

private void SomeButton_Click(object sender, EventArgs e){

Timer1.Enabled = false();

// Do stuff here…

// Maybe reenable the timer here…

}

Hmmm… that doesn’t seem to work, and here’s why. Since the submit button click is handled server-side, the enabling-disabling action won’t be propagated back to the client until the postback is complete. The timer is a client-side javascript control, so it can (and will) keep working as the page is being posted.

So, what do you do? Well, you’re only really left with one option – disable the timer control on the client side. That means you’re going to be doing it via Javascript. Luckily, I found this post that details all about using Javascript to disable the timer control. Now, all you have to do is hook up a client side event to the timer control and programatically disable it. You can re-enable it in codebehind with the button click handler, too, so you don’t have to do that on the client side. Here’s what I ended up with:

<script language=”javascript” type=”text/javascript”>
<!–
function DisableTimerControl(){

// Disable the ajax timer control before elevating on the client side.
// It will be re-enabled on the server side.
var timerControl = $find(“AjaxUpdateTimer”);

if (timerControl != null){

timerControl._stopTimer();

}
return true;

}
–>
</script>

That wasn’t so bad, was it now? The long and the short of it is that you have to be careful about using Ajax controls, but it is still pretty easy to make them do what you want if you’re on top of things. Either way, Ajax is here to stay, so get used to it!