c# - do asp page variables not persist? -


i have following test asp page:

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title></title> </head> <body>     <form id="form1" runat="server">     <div>         <asp:label id="label1" runat="server" text="label"></asp:label>         <asp:button id="button1" runat="server" text="button" onclick="button1_click" />     </div>     </form> </body> </html> 

with following code behind:

public partial class test : system.web.ui.page {      int x = 0;      protected void page_load(object sender, eventargs e)     {         label1.text = x.tostring();     }      protected void button1_click(object sender, eventargs e)     {         x++;         label1.text = x.tostring();     } } 

from non web programming mindset have thought int x have been sort of object field test page class , when x++ value of x persist through postbacks seems not case. how these feilds work in terms of persistance? find odd because when click button label1.text changed 1 first time click can't past 1 after that.

then once understand why happening easiest way make happen wanting? (value of x persists across postbacks)

this looks using viewstate looking for:

public partial class test : system.web.ui.page {

//static int x = 0;    protected void page_load(object sender, eventargs e) {      if (viewstate["x"] == null)     {         viewstate["x"] = 0;         label1.text = viewstate["x"].tostring();     }       //label1.text = x.tostring(); }  protected void button1_click(object sender, eventargs e) {      viewstate["x"] = convert.toint32(viewstate["x"].tostring()) + 1;     label1.text = viewstate["x"].tostring();     //x++;     //label1.text = x.tostring(); } 

}

x not persisted. upon each request, x initialised 0.

use, example, session state store value of x e.g. session["x"] = x;

as label text, asp.net store inside of viewstate, persists control values on each request. can use viewstate if want store value used on 1 page. use session if want value available on other pages in site.

viewstate["x"] = x;


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -