Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing an List<int> in viewstate

I have an aspx page which has the following:

  • A repeater with a linkbutton in each
  • The link button has a commandargument of an integer value
  • A user control

The idea is that when the user clicks on the linkbutton the value of the commandarguement is stored in a List. No problem you may think, however I need the value to be stored in an List in the usercontrol, not in the ASPX page. The List needs to be persisted across postbacks, so it also needs to be stored in the viewstate.

So I created a public property in the user control like so:

public List<int> ImageString {
    get {
        if (this.ViewState["ImageString"] != null) {
            return (List<int>)(this.ViewState["ImageString"]);
        }
        return new List<int>();
    }
    set { this.ViewState["ImageString"] = value; }
}

And then I was hoping that from my aspx page I could add a line of code to add a value to the list like so:

this.LightBoxControl.ImageString.Add(value);

The problem I'm getting is that the the value is actually never added to the list. The count is always zero.

I'm sure its just that I've set the property up wrong, but I'm not sure how to right it..

Any help would be greatly appreciated.

Thanks Al

like image 690
higgsy Avatar asked Sep 08 '11 09:09

higgsy


People also ask

Can we store object in ViewState?

You cannot store it in ViewState.

How much data we can store in ViewState?

The more data stored in viewstate, the slower the page will load. But to answer your question, there is not a size limit to viewstate.


1 Answers

Your getter is wrong. This is the correct variant:

get {
    if (this.ViewState["ImageString"] == null) {
        this.ViewState["ImageString"] = new List<int>();
    }
    return (List<int>)(this.ViewState["ImageString"]);
}

Here you first check whether there is something you need in ViewState already, and if there is no, you add it there. Then you return the item from ViewState - it is guaranteed to be there.

Your solution was bad because it did not place new List<int>() into the ViewState

like image 114
Michael Sagalovich Avatar answered Oct 05 '22 09:10

Michael Sagalovich