I get an obscene amount of email. Since I’ve been working with the Developer Community at Microsoft for 7 years, my email address has been spread around a bit. I get about 1000 email a day. Very often from developers who what me to write code for them 🙂
I generally don’t have time to do that, but sometimes I get an email from someone why has really tried to solve a problem that should be simple, but whose answer is not always as obvious as the problem would lead you to believe.
This week a Developer emailed me about updating an UpdatePanel.
One of the true strengths of ASP.NET is the ability to take several different approaches to writing applications based on your needs and preferred development style.
The problem was, the developer was using the UpdatePanel and, due to functionality in the business layer, he needed to prevent the user from click a submit button twice in a row. Meaning, when the user clicks the button that caused the UpdatePanel to update, he needed that buttonto be disabled until the UpdatePanel’s refresh was complete.
Then, after the click but before the UpdatePanel has completed it’s update…..
And yes… I know that in a real application one should add some updating indicator.
So, the UpdatePanel definition looks like this.
23 <asp:UpdatePanel ID="UpdatePanel1" runat="server">
25 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
26 <br />
27 <br />
28 <asp:Label ID="Label1" runat="server" Text="Label" Width="622px"></asp:Label><br />
29 <br />
33 <br />
34 <input id="SubButton" style="width: 618px" type="button" value="Call UpdatePanel Method" onclick="return SubButton_onclick()" />
35 <br />
36 <br />
Note that the HTML button control "SubButton" is outside the UpdatePanel and is not defined as a Trigger to the UpdatePanel.
If you use an ASP.NET Button control and disable the Button with an OnClientClick event handler, that code fires first and the postback never occurs.
6 function SubButton_onclick()
8 var prm = Sys.WebForms.PageRequestManager.getInstance();
9 var mybutton = document.getElementById(‘SubButton’)
10 mybutton.disabled = true;
11 prm._doPostBack(‘UpdatePanel1’, ”);
13 // –>
Hopefully the code is self explanatory.
The Button is disabled and the UpdatePanel postback is triggered.
But…. How do we know when the update is complete so we can re-enable the Button.
39 var prm = Sys.WebForms.PageRequestManager.getInstance();
43 function EndRequest(sender,args)
45 var mybutton = document.getElementById(‘SubButton’);
46 mybutton.disabled = false;
Luckily, the PageRequestManager is throughly evented. :)
We just add an "EndRequest" event handler and have it re-enable the Button.
Pretty simple after you see the solution 🙂