Note that there are some explanatory texts on larger screens.

plurals
  1. POdo asp page variables not persist?
    primarykey
    data
    text
    <p>I have the following test ASP page:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:Label ID="Label1" runat="server" Text="Label"&gt;&lt;/asp:Label&gt; &lt;asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>with the following code behind:</p> <pre><code>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(); } } </code></pre> <p>From a non web programming mindset I would have thought that <code>int x</code> would have been a sort of object field for the test page class and that when i do <code>x++</code> the value of <code>x</code> would persist through postbacks but it seems this is not the case. So how exactly do these feilds work in terms of persistance? I find it odd also because when you click the button the <code>Label1.Text</code> is changed to 1 the first time you click it but you can't get it past 1 after that.</p> <p>Then also once I understand why this is happening what is the easiest way to make happen what I was originally wanting? (value of <code>x</code> persists across postbacks)</p> <p>This is what it looks like now using viewstate which is what i was looking for:</p> <p>public partial class test : System.Web.UI.Page {</p> <pre><code>//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(); } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload