繁体   English   中英

在ASP.NET页中存储会话变量?

[英]Storing session variables in ASP.NET page?

如何将具有整个会话范围的变量放到ASP.NET页上(我的意思是站在aspx页后面的类中)? 将变量放入Session对象的唯一方法是吗?

例如:

public partial class Test_ : System.Web.UI.Page
{
    private int idx = 0;

    protected void Button1_Click(object sender, EventArgs e)
    {
        Button1.Text = (idx++).ToString();
    }
}

我希望每次单击此按钮时索引都会上升。 不使用Session对象怎么办?

Danail提前10倍

您可以将其放在ViewState

public partial class Test_ : System.Web.UI.Page {

    protected void Button1_Click(object sender, EventArgs e) {
        if(ViewState["idx"] == null) {
            ViewState["idx"] = 0;
        }
        int idx = Convert.ToInt32(ViewState["idx"]);

        Button1.Text = (idx++).ToString();

        ViewState["idx"] = idx;
    }
}

只要不需要在此页面范围之外维护该计数器,就可以在这里找到ViewState。 请记住,页面刷新将重置计数器。 另外,如果计数器是敏感信息,请注意它将被存储(加密)在呈现的HTML中,而会话值则存储在服务器端。

除会议外,还有许多其他选择。 看看在ASP.NET应用程序中管理持久用户状态的九个选项

对于此类数据,您可能需要使用会话存储。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM