Question

I have this sample below:

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">

    <script type="text/javascript">
function test(){

if (test.initialized=='undefined'){
    test.initialized = 'true';
    }

alert(test.initialized);

};
    </script>

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <asp:Button ID="btnPostBack" runat="server" Text="Post back" OnClientClick="test()" />
</asp:Content>

When I click post-back on the page, I found out that the variable initialized -which is defined on the function itself- is loosing its value and becoming 'undefined' again.

Is it possible to keep those static values once they are defined and make them unaffected from any post backs on the page?

Was it helpful?

Solution

You could add them as a query string or keep them in a cookie.

OTHER TIPS

Maybe you want to do something like this. I also think that you are confusing test function with test object.

var initialized = false;
function test(){
    if ( !initialized){
        initialized = true;
    }
};
            alert(initialized); // false
            test();
            alert(initialized); //true

javascript is going to be re-executed on postback as the page reloads (unless you are using update panels).

to preserve a client side value, write the value into an asp hidden field using JS, and don't render the javascript if IsPostBack is true so that it doesn't get overwritten on postback

I think using partial-post back is a way as well.

If it is not possible, only by using Java script I think cookies can be another way as long as they are not turned of by the user.

My feeling is the best way is to design the page in a way that I would not need to store it :)

You could add a hidden field and set the value of this? I think this way it'll be preserved in the viewstate, and you can load its value back into your variable with something like:

var p = '<%=blah.Text%>';

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow