views:

340

answers:

5

Hi,

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?

+2  A: 

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

matpol
adding them to the querystring can be a bit of a pain with WebForms. Cookies might be disabled (maybe)
mcintyre321
if it's a pain use the method below(Paul Deen) where the js var is added as (not actually sure what language this) var.
matpol
A: 

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
Elzo Valugi
A: 

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

mcintyre321
A: 

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 :)

burak ozdogan
A: 

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%>';

Paul Deen