1

我试图了解这里发生的生命周期。我有一个 asp 列表视图,我在其中获取项目 ID 并将它们写入这样的列表。

 protected void ShareWith_OnItemBound(object sender, ListViewItemEventArgs e)
    {
        if (!IsPostBack)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                ListViewDataItem currentItemId = (ListViewDataItem)e.Item;
                System.Web.UI.WebControls.DataKey currentDataKey = this.lvShareWithPanel.DataKeys[currentItemId.DataItemIndex];
                int FriendId = Convert.ToInt32(currentDataKey["SharedUserId"]);
                CurrentList.Add(FriendId);
            }
        }
    }

我的列表是在方法之外定义的

private List<int> CurrentList = new List<int>();

之后,用户将一些新项目添加到列表中,然后单击 asp 按钮继续。我正在比较当前列表与新列表,但在单击按钮后在调试中观察我发现我的列表“CurrentList”现在为空。为什么在任何方法之外的列表可能会受到影响?

感谢帮助理解

4

4 回答 4

3

该列表没有状态值。因此,您需要将列表存储在 ViewState、Session 状态或其他状态。

每个 ASP.NET 页面在页面加载之间都会丢失其值,并且只有在每次都输入它们时才能从状态中恢复它们。大多数控件将值存储在特定于页面的 ViewState 中。这个链接应该有帮助。

于 2012-10-08T09:28:47.193 回答
2

所有页面的对象都将在页面生命周期结束时被释放。因此,您需要在每次回发时创建并填写您的列表(或将其存储在Session我不推荐的地方)。

您可以使用页面的PreRender事件来确保所有事件都已被触发:

protected override void OnPreRender(EventArgs e)
{
    // why do you need a list as field variable at all? I assume a local variable is fine
    List<int> CurrentList = new List<int>();
    foreach(var currentItemId in lvShareWithPanel.Items)
    {
        System.Web.UI.WebControls.DataKey currentDataKey = lvShareWithPanel.DataKeys[currentItemId.DataItemIndex];
        int FriendId = Convert.ToInt32(currentDataKey["SharedUserId"]);
        CurrentList.Add(FriendId);
    }
    // do something with the list
}

请注意,您不应该static像有人评论的那样做到这一点。这意味着您将为每个用户和每个请求使用相同的“实例”。

在这里您可以看到所有事件:

在此处输入图像描述

于 2012-10-08T09:27:23.787 回答
2

ASP.NET 是无状态的,因此在回发期间数据会丢失。您需要手动跟踪,CurrentList例如在 Session/ViewState 中。

public List<int> CurrentList
{
    get
    {
        return (List<int>)Session["CurrentList"] ?? new List<int>();
    }
    set
    {
        Session["CurrentList"] = value;
    }
}
于 2012-10-08T09:27:46.610 回答
0

您可以将列表存储到 ViewState 中,并在 PageLoad 事件中,将存储在 ViewState 中的列表分配给您的类级别列表。这是因为处理对象的页面生命周期。

于 2012-10-08T09:30:06.327 回答