views:

1027

answers:

3

I'm using ASP.NET Ajax with JQuery. I have a click event that adds/removes css classes on objects in an UpdatePanel, but when the ASP.NET Partial postback occurs, I lose the "state." Here is minimal example I tried to create; how do I keep the css class state?

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title></title>

    <style type="text/css">
        .active { background: #000000; color: #ffffff; }
        .test {}
    </style>


    <script src="jquery-1.3.2.js" type="text/javascript"></script> 

    <script language="javascript" type="text/javascript">

        function pageLoad(sender, args) {

            // rebind events lost in partial postback
            $(".test").unbind();

            $(".test").click(function() {

                $(".test").removeClass("active");
                $(this).addClass("active");

            });

        }

    </script>








</head>
<body>
    <form id="form1" runat="server">


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

    <asp:Timer ID="Timer1" runat="server" Interval="30000" ontick="Timer1_Tick">
    </asp:Timer>

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

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

    <ContentTemplate>


    <div class="test">

        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    </div>


    <div class="test">

        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>

    </div>

    </ContentTemplate>
    </asp:UpdatePanel>

    </form>
</body>
</html>
A: 

The updatepanel replaces the DOM within its scope, so any modifications you make won't persist between postbacks.

You might look into jQuery "live" events which (supposedly - I haven't tried) reapply themselves when new elements are added into the document.

David Lively
A: 

Look into using the client PageRequestManager events to save/restore state (note, the following is JavaScript):

function SaveState(sender, args) 
{
  // code to save state of update panel controls
}

function ReapplyState(sender, args)
{

  // code to reapply state of update panel controls
}

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(SaveState);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(ReapplyState);
zincorp
could you elaborate? how would I save state? in global js variables, session variables, ?? private variables in code-behind seem to lose their value (state) in partial postback
Through global js variables. They won't change since the page remains and only a portion is being updated.The code above is all JavaScript
zincorp