views:

25

answers:

3

I have a class level price variable decalred inside a page, like this:

public partial class _Default : System.Web.UI.Page 
{
    private MyClass myVar = new MyClass();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            myVar.LoadData();
            myVar.ShowData();
        }
    }

    protected void cmdRefresh_Click(object sender, EventArgs e)
    {
        myVar.ShowData();
    }
}

The problem I have is that after the initial load, the first time that the button is pressed it seems to reset myVar, and all its data is lost. Is this a known issue with ASP.NET and is there a workaround?

+2  A: 

The variable myVar will never be persisted across postbacks, you need to use some method of caching, such as Application / Session / ViewState / Cookies.

bleeeah
+4  A: 

Hi there.

Use the ViewState to store the class, if you just need to save the classfor the current page. IF you want to save it for the entire site, then look into things like Sessions.

private MyClass myClass
{
    get {
      if (this.ViewState["myVar"] != null)
      {
           return (MyClass)this.ViewState["myVar"];
      }
    }
set{
     this.ViewState["myVar"] = value;
}
}

Cheers. Jas.

Jason Evans
Damn! Too quick for me!
5arx
A: 

Yes that is a know functionality. Basically you page object is created for every request, so properties are set for you (IsPostBack being one of them) but you need to take steps you self to make sure that fields (declared in code) is populated every time. In this particular case either by fetching Them or keeping Them in the form (viewstate) or session data. Which one to choose should depend on such as size of data, time to refetch, data store loads etc.

Rune FS