开发者

List goes from count of 1 to 0 between two operations, with no code to do so. (asp.net)

开发者 https://www.devze.com 2023-03-16 06:29 出处:网络
I\'ve got the following list List<int> deletedRecords = new List<int>(); When I hit the delete button in my gridview, I add the Id for that record to this List.

I've got the following list

List<int> deletedRecords = new List<int>();

When I hit the delete button in my gridview, I add the Id for that record to this List.

When the user clicks the save button, all records that exist in the List are deleted from the database before I proceed.

However, when I get to this point, the List is always empty.

The List is only referenced in three places, those being its declaration, its .Add method, and a foreach to cycle through all values it contains.

When I do a debug, I can see the List.Count go to 1, but then when I h开发者_Go百科it the Save button, my Debug shows the List has gone to a count of 0. I'm really confused by this.

Can anyone help?


The list variable / field only exists for the duration of a single request; any button-click (such as Save) is a separate request, with an entirely different set of objects. In many cases it won't even be served by the same server.

If you need state between requests, you need to manage that state, perhaps via session-state.


Without seeing any code, I'd guess the following:

You've forgotten web apps have no state.


As Marc and Esteban said, you have to persist your items.

So instead of writing

List<int> deletedRecords = new List<int>();

you could write

private List<int> deletedRecords
{
    get
    {
        var result = ViewState["deletedRecords"] as List<int>;

        if ( result == null )
        {
            result = new List<int>();
            ViewState["deletedRecords"] = result;
        }

        return result;
    }
}

and use this property of your page class instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消