Dan Lister
Dan Lister

Reputation: 2583

How to maintain div contents after post back?

I have a panel on a page which it's contents are changed client side. For example, I have the following web form:

<asp:panel id="panContents" runat="server">
    <span>Initial content</span>
</asp:panel>

The following jQuery snippet replaces the contents of the div client side when the page is first loaded:

$("<%= panContents.ClientId =>")
    .html("<span>Some content to be maintained after postback</span>")

After the page is submitted and returned to the client, the contents of the panel reverts back to as when the page was first loaded:

<div>
    <span>Initial content</span>
</div>

Is it possible to maintain the contents of the panel after post back so that it appears the same before being submitted? So I end up with the following after post back:

<div>
    <span>Some content to be maintained after postback</span>
</div>

Upvotes: 0

Views: 1763

Answers (2)

cachet.net
cachet.net

Reputation: 320

The content of panel vanishes because you are just manipulating the DOM. If you want to retain the value of panel first put it into a hidden field and after post back reassign the text to panel

Upvotes: 1

Andrei
Andrei

Reputation: 56688

This content exists only on a client, since Panel does not post any content to the server (somewhat obviously). The workaround you might want to apply to check if you need to run the snippet on the page load. For this you might want a hidden field with a flag.

Here is a dirty proof of concept:

<asp:HiddenField ID="ReplacePanelFlag" runat="server" Value="0" />

// check flag on page load
$(function() {
    if ($("<%= ReplacePanelFlag.ClientID %>").val() === "1") {
        //run snippet
    }
});

// in snippet make sure to set the flag to "1"
$("<%= panContents.ClientId =>")
.html("<span>Some content to be maintained after postback</span>");
$("<%= ReplacePanelFlag.ClientID %>").val("1");

Upvotes: 1

Related Questions