【问题标题】:C#: Changing code from Session to ViewState causing page refreshC#:将代码从 Session 更改为 ViewState 导致页面刷新
【发布时间】:2015-09-26 22:50:11
【问题描述】:

我有一个包含一些用户控件的页面。这些 UC 有一些内容是否可见,具体取决于您单击的位置。 此页面使用 Sessions 来保留数据库中的数据,如下所示:

private ViewPersonCollection collection
    {
        get
        {
            if (Session["ViewPersonCollection.test1"] == null)
                Session["ViewPersonCollection.test1"] = new ViewPersonCollection ();
            return (ViewPersonCollection )Session["ViewPersonCollection.test1"];
        }
        set { Session["ViewPersonCollection.test1"] = value; }
    }

由于当客户端在同一个浏览器中使用不同的选项卡时会话出现一些问题,我将其更改为视图状态,如下所示:

private ViewPersonCollection collection
    {
        get
        {
            if (ViewState["ViewPersonCollection.test1"] == null)
                ViewState["ViewPersonCollection.test1"] = new ViewPersonCollection ();
            return (ViewPersonCollection )ViewState["ViewPersonCollection.test1"];
        }
        set { ViewState["ViewPersonCollection.test1"] = value; }
    }

但在此更改之后,我的页面停止加载用户控件。如果我点击一个按钮,页面会重新加载。我调试了它,代码运行正常,但由于某种原因,主页正在重新加载。

这是怎么回事?

【问题讨论】:

  • 点击查看源代码,看看你有多大的viewState,在viewstate中存储大对象不是最佳做法,因为viewstate是简单的隐藏字段,html文件的大小变得很大

标签: c# asp.net session viewstate page-lifecycle


【解决方案1】:

每个用户控件都使用自己的 ViewState,该 ViewState 稍后会与页面 ViewState 合并。无论如何,ViewState 对于大对象来说不是一个好的选择。

您可以尝试使用 this.Context.Item 集合,它将在您的用户控件和您的页面之间共享,但它只会在同一个 HTTP 请求中保存信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-30
    • 2011-10-10
    • 1970-01-01
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多