Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 308
  • Last Modified:

How can I get page variable values to persist accross postbacks?

I heard a developer tell me asp.net page variables persisted across postbacks, but I haven’t ever seen this work, can it?

so if I have a page like so:

namespace blah
{
      public class page : System.Web.UI.Page
      {
            protected int imageID;

            private void Page_Load(object sender, System.EventArgs e)
            {
                  if (!IsPostBack) imageID = 5;
            }
      }
}

how can I get the imageID property to keep it's value on a postback?

bd
0
brooklynDev
Asked:
brooklynDev
  • 2
1 Solution
 
softplusCommented:
Try a bit of Viewstate: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspnet/html/asp11222001.asp
:)
or add a hidden literal/label/field to the page
0
 
BurntSkyCommented:
softplus is correct; throw that variable in the ViewState bag and grab it in your postback.  Something kind of like this:

private void Page_Load(object sender, System.EventArgs e)
{
   if(!this.IsPostBack || ViewState["imageID"] == null)
   {
      this.imageID = 5;
      ViewState["imageID"] = this.imageID;
   }
   else
      this.imageID = (int)ViewState["imageID"];
}
0
 
brooklynDevAuthor Commented:
so I take it that dev I was talking about was wrong, and page variables as illustrated in my question can and do not persist across postbacks
0
 
BurntSkyCommented:
That's correct; imageID, in the code you posted, will not retain its value across postbacks.
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now