开发者

Storing session variables in ASP.NET page?

How can I put variables that have scope the whole session on ASP.NET Page (I mean in the class that stands behind the aspx page)? Is the only way to put the variable in the Session object?

For example:

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

    protected void Button1_Click(object sender, EventArgs e)
    {
        Button1.Text = (idx+开发者_开发知识库+).ToString();
    }
}

I want on every click on this button my index to go up. How can I do this without using the Session object?


You can put it in ViewState instead

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 seems to be what you're looking for here, so long as that counter doesn't need to be maintained outside the scope of this page. Keep in mind that a page refresh will reset the counter though. Also, if the counter is sensitive information, be wary that it will be stored (encrypted) in the rendered HTML whereas Session values are stored server-side.


There are a number of options besides the session. Take a look at Nine Options for Managing Persistent User State in Your ASP.NET Application.

For this sort of data, you probably would want use the session store.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜