How to declare session variable in C#? [duplicate]

隐身守侯 提交于 2019-12-07 16:29:16

问题


I want to make a new session, where whatever is typed in a textbox is saved in that session. Then on another aspx page, I would like to display that session in a label.

I'm just unsure on how to start this, and where to put everything.

I know that I'm going to need:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["newSession"] != null)
    {
        //Something here
    }
}

But I'm still unsure where to put everything.


回答1:


newSession is a poor name for a Session variable. However, you just have to use the indexer as you've already done. If you want to improve readability you could use a property instead which can even be static. Then you can access it on the first page from the second page without an instance of it.

page 1 (or wherever you like):

public static string TestSessionValue 
{ 
    get 
    {
        object value = HttpContext.Current.Session["TestSessionValue"];
        return value == null ? "" : (string)value;
    }
    set 
    {
        HttpContext.Current.Session["TestSessionValue"] = value;
    }
}

Now you can get/set it from everywhere, for example on the first page in the TextChanged-handler:

protected void TextBox1_TextChanged(Object sender, EventArgs e)
{
    TestSessionValue = ((TextBox)sender).Text;
}

and read it on the second page:

protected void Page_Load(Object sender, EventArgs e)
{
    this.Label1.Text = Page1.TestSessionValue; // assuming first page is Page1
}


来源:https://stackoverflow.com/questions/16407502/how-to-declare-session-variable-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!