views:

136

answers:

3

How do I persist an ASP.Net class on PostBack? I've already taken the time to go to the database and fill my object with values when the page loads initially, so how can I save this object in an elegant way on a PostBack? The page that contains the custom object posts back to itself.

For what it's worth I'm using C# in an ASP.NET 3.5 Web Forms application.

+2  A: 

There may be a better way to do this with 3.5, but in 2.0 you could use the viewstate. Just add the object to the viewstate and it is automatically included in the default asp.net form as a hidden field. Then on the postback you can retrieve it from the viewstate.

Be careful with it though, your viewstate is included on every page load. Ultimately I would recommend just fetching the object again from the database and avoiding the viewstate. You could also try something like memcached to cache the object server side.

    protected void Page_Load(object sender, EventArgs e)
    {
        if(ViewState["NameOfUser"] != null)
            NameLabel.Text = ViewState["NameOfUser"].ToString();
        else
            NameLabel.Text = "Not set yet...";
    }

    protected void SubmitForm_Click(object sender, EventArgs e)
    {
        ViewState["NameOfUser"] = NameField.Text;
        NameLabel.Text = NameField.Text;
    }

Example from http://asp.net-tutorials.com/state/viewstate/

vfilby
A: 

You could use a session variable or server caching. One limit with viewstate is the object has to be serialized to store it, but session and server caching can store any object.

derek
Session may require the object to be serialized, depending upon how the session store has been setup.
Jason Berkan
A: 

If the object is small you may consider persisting it to a hidden field(s). That way you are not having to take up server memory, but you also avoid hitting the database again.

Jason Webb