Search code examples
c#.netasp.netdataobjects.net

Hold a data structure over several pages?


I'm using .NET 3.5 and I need some help with how to hold a data object when you transfer between different pages.

This is my setup:

I have a four step registration where each step includes its own web page. I want to be able to hold a object in memory between the pages without saving it to the database. Each page will add something to this object.

Just for the ease of it, lets say I have a object like

public class MyObject
{
    private int myNumber;
    private String myName;
    private List<Person> myFriends; //Person is simply a class that has a Strign name with getter and setters. 
    public MyObject()
    {
        myFriends = new List<Person>();
    }

    public void setMyNumber(int i){
        myNumber = i;
    }

    public void setMyName(String n)
    {
        myName = n;
    }

    public void setMyFriends(List<Person> li)
    {
        myFriends = li;
    }

    public void addFriend(Person p)
    {
        myFriends.Add(p);
    }

}

When I then get to the last page and have collected all the data, then I will commit it to my database. What is the best way to do this in c#? Any nice links or samples would be great!


Solution

  • You can use session/cookie to hold the data.

    See the sample code of how to use session below.

    How to: Save Values in Session State

    string firstName = "Jeff";
    string lastName = "Smith";
    string city = "Seattle";
    Session["FirstName"] = firstName;
    Session["LastName"] = lastName;
    Session["City"] = city;
    

    How to: Read Values from Session State

    string firstName = (string)(Session["First"]);
    string lastName = (string)(Session["Last"]);
    string city = (string)(Session["City"]);
    

    Reference:
    http://msdn.microsoft.com/en-us/library/ms178581.aspx#CodeExamples