如何在 C# 中声明会话变量? [英] How to declare session variable in C#?

查看:62
本文介绍了如何在 C# 中声明会话变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个新会话,在该会话中保存在文本框中键入的任何内容.然后在另一个 aspx 页面上,我想在标签中显示该会话.

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.

我知道我需要:

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

但我仍然不确定把所有东西放在哪里.

But I'm still unsure where to put everything.

推荐答案

newSessionSession 变量的一个糟糕名称.但是,您只需要像之前一样使用索引器即可.如果你想提高可读性,你可以使用一个甚至可以是静态的属性.然后你可以从第二页访问第一页而不需要它的实例.

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.

第 1 页(或任何您喜欢的地方):

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;
    }
}

现在你可以从任何地方获取/设置它,例如在 TextChanged-handler 的第一页:

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;
}

并在第二页阅读:

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

这篇关于如何在 C# 中声明会话变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆