CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2005
    Posts
    33

    Objects between postbacks

    Hello,

    Help me please with something that I think is very basic...

    1. Suppose I have a class called MyClass. It is placed in App_Code folder of my web-application:

    public class MyClass
    {
    private IView view;
    private DateTime time;

    public MyClass(IView view)
    {
    this.view = view;
    }

    public DateTime Time
    {
    get { return time; }
    set { time = value; }
    }

    // Here comes some other code...
    }

    2. Now, I have an ASPX page called MyPage.aspx. It implements the IView, it has a private member of type MyClass, and here are some relevant methods:

    public partial class MyPage: System.Web.UI.Page, IView
    {
    private MyClass myClass;

    // CTOR
    public MyPage()
    {
    myClass = new MyClass(this);
    }

    protected Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack) { myClass.Time = DateTime.Now; }
    }

    protected MyButton_Click(object sender, EventArgs e)
    {
    lblTime = myClass.Time;
    }

    // Here comes some other code
    }

    Ok. What I am expecting is:
    - MyPage CTOR creates an object of type MyClass;
    - Then Page_Load sets the current time;
    - Then the user clicks MyButton and the stored time is displayed in MyLabel.

    So actually I expect that the MyClass object will be stored in the current session and behave like it would behave in usual non-Web application.

    But... I get something strange. First of all, the "time" member of myClass is NOT stored. Well, I know about this kind of problems, so I know that I should probably use Session[] to store the values. But the strange thing is that the "view" member IS stored! I can see that using the debugger...

    So please explain me, when the variables ARE stored between postbacks and when they ARE NOT... Thank you!

  2. #2
    Join Date
    Aug 2004
    Location
    Land of sunshine and June Gloom
    Posts
    171

    Re: Objects between postbacks

    Use the ViewState to store objects between postback e.g.

    public MyClass SomeProperty
    {
    get { return ViewState["SomeProperty"] as MyClass; }
    set { ViewState["SomeProperty"] = value; }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured