Home > .net 2.0, AJAX, JavaScript, Visual Studio 2005 > Refreshing an AJAX UpdatePanel with JavaScript

Refreshing an AJAX UpdatePanel with JavaScript

July 4, 2007

A forum post came across today regarding updating a UpdatePanel using JavaScript “on demand”.  I piecemealed some code together a few months ago from various blog posts, forum posts, and general trial and error–and it worked fairly well.

On our page, we’ll need a simple JavaScript.  This could be inline or an external .js file, whichever works for your project.

<script type=”text/JavaScript”>  
function updatePanelPostback(ClientId)
{
        __doPostBack(ClientId,
);
}
</script>
 
The above JavaScript uses the specified clientId (that we’ll specify later) and provides a postback based on it.  In this function, we can also capture text events and do other data collections and such on the page if needed.  Wrapping this in a function provides that capability rather than simply calling __doPostBack in our event (though it is possible, I’ll show both).

UpdatePanel1: <asp:TextBox ID=”TextBox1″ runat=”server”
onKeyUp=”javascript:updatePanelPostback(‘upHiddenPostback1’)”>
</
asp:TextBox>
<br />
 
<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server” UpdateMode=”Conditional”>
    <contenttemplate>
        <asp:GridView ID=”GridView1″ runat=”server” DataSourceID=”SqlDataSource1″>
        </asp:GridView>
        <asp:Label ID=”Label1″ runat=”server” />
        <asp:HiddenField runat=”server” ID=”upHiddenPostback1″ />
        
        
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
        
ConnectionString=”<%$ ConnectionStrings:SandboxConnectionString1 %>
        
SelectCommand=”SELECT * FROM [staff] WHERE Id = @Id”>
        <SelectParameters>
        <asp:ControlParameter ControlID=”TextBox1″ Name=”Id” />
        </SelectParameters>
        </asp:SqlDataSource>
    </contenttemplate>
</asp:UpdatePanel>
 
As I stated above, here are the two examples, either calling our JavaScript function, or doing it inline.  In this example, I have a GridView that is updated dynamically as you “type” into the TextBox since our Postback is generated onKeyUp event.  The TextBox, if the function wasn’t used, could also be coded as below.  Since I’m not adding any additional functionality at this time, they are both equal.
 
<asp:TextBox ID=”TextBox1″ runat=”server”
onKeyUp=”javascript:__doPostBack(‘upHiddenPostback1′,’);”></asp:TextBox>
 
I placed and additional GridView (that simply looks at all records rather than by Id) with the DateTime to give a comparison.  The end result looks like:
 
 
%d bloggers like this: