Refresh the UpdatePanel using JavaScript Code

(It's the post I wrote one year ago in my previous blog which has been cancelled now.)

Lots of customers asked me that how to refresh the UpdatePanel - it actually is to raise an async postback using JavaScript code. The feature is quite important in some scenarios but unfortunately, ASP.NET AJAX does not give any native support, so we should find work arounds to do that.

An UpdatePanel will be refreshed if the user clicks the specific control in the page and the control is the trigger that raises the async postback. The straightest thought of raising an async postback is to simulate a button's clicking. There're several kinds of buttons in ASP.NET (we use the concept in ASP.NET rather than the concept in HTML since the server side konws ASP.NET better). They are Button, LinkButton, ImageButton, etc. Let's just look at the LinkButton control since it will shows the things we need. (I use an master page here to show the effect of NamingContainer.):

<!-- Declarative code in ASPX page -->
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>

<!-- The html generated in client side -->
<a id="ctl00_Main_LinkButton1" href="javascript:__doPostBack('ctl00$Main$LinkButton1','')">
    LinkButton
</a>

A LinkButton on server side generates an anchor tag on the page. The way to submit the form when click the anchor is to execute the JavaScript method "__doPostBack". Please note that it's really simple for us to simulate that. The only thing we should pay attention to is the first parameter passed to the method. What's that?

An experience ASP.NET programmer will easily figure out that a string separated by dollar signs ($) is most likely the UniqueID of the control, which is used to indicate the control at server-side, and then the proper event will be raised, etc. So, if we are going to simulate the postback raised by the LinkButton, its UniqueID shoud be write to clint side for further use.

I'm going to show you a demo here to tell the way discussed above. At first, we should build a page with an UpdatePanel and a invisible LinkButton in it. Please note that we set the style of the LinkButton to "display:none" rather than set its Visibile property to false, otherwise the LinkButton won't be rendered on the page, which will cause an exception when postback:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <%= DateTime.Now %>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:LinkButton ID="LinkButton1" runat="server" style="display:none;">
    LinkButton
</asp:LinkButton>

Secondly, write the following code to the page. You can find that we should write the UniqueID of the LinkButton to the client:

function raiseAsyncPostback()
{
     __doPostBack("<%= this.LinkButton1.UniqueID %>", "");
}

The last thing to do is to make the LinkButton raising an async postback, so add the code to the code behind file:

ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.LinkButton1);

Now we can simply call the raiseAsyncPostBack method defined in the page when we want to raise an async postback using JavaScript code. Both the client and server will think the LinkButton is clicked. The client side will raise an async postback and the server will fire the Click event of the LinkButton. If we want to refresh some UpdatePanels when we execute the JavaScirpt method, we can just assign the LinkButton to the UpdatePanels as an AsyncPostBackTrigger.

Published Saturday, April 26, 2008 9:38 PM by JeffreyZhao

Comments

# re: Refresh the UpdatePanel using JavaScript Code

Sunday, April 27, 2008 1:05 PM by Guy Harwood

thanks for this Jeff, ive been musing over different ways to accomplish this in the last few days.

this is a nice and simple solution

# Build a Simple Control to Refresh UpdatePanel from Client Side

Sunday, April 27, 2008 9:25 PM by Happy Coding

All we should do for the current feature is just to generate JavaScript proxies in the page. Actually I've also build an simple control to help the devs to raise async postbacks from client side, encapsulated the way described in this post.

# re: Refresh the UpdatePanel using JavaScript Code

Tuesday, May 27, 2008 10:33 AM by dBrown

Tried this and works in IE but in Firefox a full postback occurs (IsInAsyncPostBack = false and IsPostBack = true). Anyone else have this problem or know of a solution?

# re: Refresh the UpdatePanel using JavaScript Code

Wednesday, May 28, 2008 9:42 AM by ajay

I tried it but not working. I had the following problem.

I have an update panel and i have added a asp button outside the update panel. The button had a server side click event as well. But when i saw the HTML generated in client side it is showing some thing like "<input type="submit" name="ctl00$pageBody$persistDataButton" value="tttttttttttt  tttttttt" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$pageBody$persistDataButton&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" id="ctl00_pageBody_persistDataButton" class="SubmitAsyncButton" />"

Note that it is not showing the _doPostBack method as mention in the above article. How can i get the asynchronous call in this situation

# re: Refresh the UpdatePanel using JavaScript Code

Wednesday, May 28, 2008 9:47 AM by ajay

I am using .net 3.5 version.

# re: Refresh the UpdatePanel using JavaScript Code

Wednesday, May 28, 2008 11:45 AM by dbrown

if reference to my question about FireFox not working, I found that if I include a value in the 2nd argument for the __doPostBack function, then firefox works, but if the eventArgument is blank, firefox does a full postback.

# re: Refresh the UpdatePanel using JavaScript Code

Wednesday, June 11, 2008 5:15 AM by Andre

Is there a clean working solution for firefox as well?

# re: Refresh the UpdatePanel using JavaScript Code

Friday, June 20, 2008 7:54 AM by Zaheer Rafiq (Ziggy Rafiq)

thanks for the code but it had few sytax errors which i've fixed and  it work for the page post back but does not work for stop page refresh when using asp:menu or a other asp ui to  go to other page.

below is the code which works  from your article.

<script language="javascript">

   function raiseAsyncPostback()

   {

    __doPostBack("<%= this.LinkButton1.UniqueID %>", "");

   }

   </script>

<div>

   <asp:ScriptManager ID="ScriptManager1" runat="server">

        </asp:ScriptManager>

        <asp:LinkButton ID="LinkButton1" runat="server"  Text="link" PostBackUrl="~/Default2.aspx">

   LinkButton

   </asp:LinkButton>

</asp:UpdatePanel>

 ScriptManager.GetCurrent(this.Page).RegisterAsyncPostBackControl(this.LinkButton1);

# re: Refresh the UpdatePanel using JavaScript Code

Tuesday, November 04, 2008 4:02 AM by ganesh

how can refresh the master page using javascript

# re: Refresh the UpdatePanel using JavaScript Code

Sunday, February 08, 2009 11:53 PM by Rahan

Please find below my code lines:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UCFXRates.ascx.cs" Inherits="UCFXRates" %>

<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="100000">

</asp:Timer>

<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">

   <contenttemplate>

       <table id="MainTable" cellSpacing="0" cellPadding="0" width="100%" border="0" runat=server>

           <tr>

               <td align=center>

                   <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Names="Arial" Font-Size="11px"

                       Font-Underline="True" ForeColor="Maroon" Height="10px" Width="106px" Text="Current FX Rates"></asp:Label>

                   <asp:GridView

                       ID="CurrencyGrid" runat="server" BackColor="Transparent" BorderColor="DodgerBlue" BorderStyle="Double"

                       BorderWidth="1px" CellPadding="4" GridLines="Horizontal" Height="227px" AutoGenerateColumns=false>

                       <FooterStyle BackColor="White" ForeColor="#333333" />

                       <RowStyle BackColor="Transparent" ForeColor="#333333" BorderColor="Transparent" BorderWidth="1px" Height=6px/>

                           <Columns>

                               <asp:BoundField DataField="FX_Curr" HeaderText="Curr" >

                                   <ItemStyle Width="30%" HorizontalAlign=center/>

                               </asp:BoundField>

                               <asp:BoundField DataField="FX_Curr_Against" HeaderText="Curr_Against" >

                                   <ItemStyle Width="30%" HorizontalAlign=center/>

                               </asp:BoundField>

                               <asp:BoundField DataField="ex_rate" HeaderText="EX Rate" >

                                   <ItemStyle Width="30%" HorizontalAlign=right/>

                               </asp:BoundField>

                           </Columns>

                       <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />

                       <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />

                       <HeaderStyle BackColor="RoyalBlue" Font-Bold="True" ForeColor="White" BorderColor="Blue" Height=5px/>

                   </asp:GridView>

               </td>

           </tr>

       </table>

   </contenttemplate>

   <triggers>

       <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick"></asp:AsyncPostBackTrigger>

   </triggers>

</asp:UpdatePanel>

i am using it in a user control which attached in master page to display FX rates, this making entire page to do postback, what i need is to refresh only this control without effecting entire page, any idea?

# re: Refresh the UpdatePanel using JavaScript Code

Monday, February 09, 2009 12:55 AM by Rahan

as i mentioned above just i need to refresh this user control after adding this to master page, becasue i am facing problem in entire page refreshing... please if anyone of you aware how to resolve this???

# re: Refresh the UpdatePanel using JavaScript Code

Wednesday, March 25, 2009 2:32 AM by Suyog Kale

Hi Rahan,

do you got any solution on your problem?

i also facing same problem, i want to just update user control, but it reloading whole page..

please let me know.

Suyog Kale,

+919767654573, Pune India

# re: Refresh the UpdatePanel using JavaScript Code

Tuesday, May 05, 2009 10:23 AM by atconway

I have 2 page controls using setInterval and some JS to scroll some text.  Upon completion of the scrolling I use the code from this site to fire a server side hidden button event to update the scrolling text.  Everything works fine EXCEPT when both scrolling areas finish at the same or roughly the same time and both try to call the wired up event (each has its own button event) at the same time.  Only 1 server-side event gets fired (verified by breakpoints).  If the calls are offset and do not happen at the same time, no problem both fire ok.  It is only when they both fire at the same time or even roughly the same time.  I experimented with using timers to offset the calls, and made some other work-arounds to offset the calls as a temporary resolution.

However, I would like a definitive explanation as to why if the doPostBack() call is made simultaneously with another doPostBack() call, why does only 1 of the server side events get fired?  Is there a better work around?

Thanks!

# re: Refresh the UpdatePanel using JavaScript Code

Tuesday, May 05, 2009 10:51 AM by atconway

I think I found an explination of this exact issue best described on the following site:

technicalsideofarati.blogspot.com/.../simultaneous-calls-to-server-from.html

It seems the root technical cause is the SessionState which makes sense; session state takes a reader/writer lock and blocks concurrent requests from the same user (same session).

odetocode.com/.../3648.aspx

If anybody would like to speak up on a good way of determining if a post back is in process and how to delay the second call enough time to let the 1st one complete, please let me know.

Leave a Comment

(required) 
(required) 
(optional)
(required)