I have the 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 the 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 a non web programming mindset I would have thought that int x
would have been a sort of object field for the test page class and that when i do x++
the value of x
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 Label1.Text
is changed to 1 the first time you click it but you can't get it past 1 after that.
Then also once I understand why this is happening what is the easiest way to make happen what I was originally wanting? (value of x
persists across postbacks)
This is what it looks like now using viewstate which is what i was 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();
}
}