Click here to Skip to main content
15,893,381 members
Articles / UpdatePanel
Tip/Trick

Using JQuery ajax with UpdatePanels

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
31 Jan 2012CPOL 36.8K   1   7
Updating UpdatePanels by calling JQuery.ajax() call
As you might know, JQuery and UpdatePanels are not friends. But some times we have to use JQuery.ajax() to design a small request(this could increase the permanence - smaller request means less bits to be transferred, and also a shorter waiting time between request and response.) In the same time we might need to use an UpdatePanel to hold some complex controls that change their appearance between round-trips.

as you might know, an UpdatePanel is rendered as a block (a div or a span depending on the RenderMode Property) that redraws itself every time its registered for update.

first we add the page markups.

XML
<asp:Button ID="cmdBind" runat="server" Text="Bind Some Data"  />
<table width="100%">
    <tr>
        <td style="width: 50%">
            <asp:Label ID="lblLoading1" runat="server" Style="display: none;">Loading ...</asp:Label>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:Repeater ID="SomeDataRepeater" runat="server">
                        <HeaderTemplate>
                            <ul>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <li>
                                <%#Eval("Data")%></li>
                        </ItemTemplate>
                        <FooterTemplate>
                            </ul>
                        </FooterTemplate>
                    </asp:Repeater>
                </ContentTemplate>
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="cmdBind" EventName="Click" />
                </Triggers>
            </asp:UpdatePanel>
        </td>
        <td style="width: 50%">
            <asp:Label ID="lblLoading2" runat="server" Style="display: none;">Loading ...</asp:Label>
            <asp:UpdatePanel ID="OtherDataPanel" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:Repeater ID="SomeOtherDataRepeater" runat="server">
                        <HeaderTemplate>
                            <ul>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <li>
                                <%#Eval("Data")%></li>
                        </ItemTemplate>
                        <FooterTemplate>
                            </ul>
                        </FooterTemplate>
                    </asp:Repeater>
                </ContentTemplate>
            </asp:UpdatePanel>
        </td>
    </tr>
</table>


On Page.Load handler we should add the code cmdBind.OnClientClick = String.Format("javascript:$('#{0}').show();", lblLoading1.ClientID) to show the text "Loading ..." when we click the button cmdBind.

Then on the handler we register to call the function <cond>BindSomeOtherDataRepeater() that will request the server again.
VB
Private Sub cmdBind_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdBind.Click
    BindSomeDataRepeater()
    ScriptManager.RegisterStartupScript(Me, Me.GetType, "BindSomeOtherDataRepeater", "BindSomeOtherDataRepeater();", True)
End Sub


the data to send to the server should contain __EVENTTARGET and __EVENTARGUMENT to cause a regular post-back event.

JavaScript
function BindSomeOtherDataRepeater(){
        $('#<%= lblLoading1.ClientID %>').hide();
        $('#<%= lblLoading2.ClientID %>').show();
        $.ajax({
            type: "POST",
            url: "<%= ResolveClientUrl(Me.Request.CurrentExecutionFilePath) %>",
            dataType: 'text',
            data: GetData(),
            success: function (msg) {
                $("#<%= lblLoading2.ClientID %>").hide();
                UpdateOtherDataPanel(msg);
            }
        });
}
 function GetData() {
    return {
    __EVENTTARGET : '<%= Me.UniqueID %>',
    __EVENTARGUMENT : 'other'
    };
}
 function UpdateOtherDataPanel(msg) {
 var div = toElement(msg);
 $('#<%= OtherDataPanel.ClientID %>').html($(div).html());
}
 function toElement(html) {
 var div = document.createElement('div');
    div.innerHTML = html;
    var el = div.childNodes[0];
    div.removeChild(el);
    return el;
}


we can catch this event by implementing the interface IPostBackEventHandler.

VB
Public Sub RaisePostBackEvent1(ByVal eventArgument As String) Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
    If eventArgument = "other" Then
        BindSomeOtherDataRepeater()
        UpdateOtherDataPanel()
    End If
End Sub


lastly we send the resulting html of the UpdatePanel in the response
VB
Public Sub UpdateOtherDataPanel()
    Dim div As New HtmlGenericControl("div")
    div.Controls.Add(SomeOtherDataRepeater)

    Response.Clear()
    Response.ContentType = "text"

    Dim twriter As New IO.StringWriter
    Dim writer As New Html32TextWriter(twriter)
    div.RenderControl(writer)
    Response.Write(twriter.ToString())
    Response.End()

End Sub

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) The first Ones
Jordan Jordan
-- Life is Good.
and you can make it better

Comments and Discussions

 
QuestionThanks Pin
ohara19-Jun-14 4:44
ohara19-Jun-14 4:44 
GeneralRe: OK, The first request is made by calling __doPostBack(eventt... Pin
Ali Al Omairi(Abu AlHassan)1-Feb-12 13:51
professionalAli Al Omairi(Abu AlHassan)1-Feb-12 13:51 
GeneralRe: See my friend; if you asked the same question twice, the fir... Pin
Ali Al Omairi(Abu AlHassan)31-Jan-12 5:04
professionalAli Al Omairi(Abu AlHassan)31-Jan-12 5:04 
GeneralRe: Your code is so contrived that it seems pointless. Using yo... Pin
tmbgfan1-Feb-12 10:44
tmbgfan1-Feb-12 10:44 
GeneralRe: There is no place for this responses such as this here. Insu... Pin
Not Active31-Jan-12 3:49
mentorNot Active31-Jan-12 3:49 
GeneralReason for my vote of 2 Don't see the point in using AJAX po... Pin
Not Active31-Jan-12 2:05
mentorNot Active31-Jan-12 2:05 
GeneralRe: Well ..., I don't see your mind. does it mean you don't have... Pin
Ali Al Omairi(Abu AlHassan)31-Jan-12 3:36
professionalAli Al Omairi(Abu AlHassan)31-Jan-12 3:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.