【问题标题】:How to save a session in C#?如何在 C# 中保存会话?
【发布时间】:2013-05-06 05:25:46
【问题描述】:

例如,我有

Session["PatientName"] = patientNameTextBox.Text;

textbox 中输入信息后,将单击一个按钮以保存会话,但我不太确定如何执行此操作。

感谢任何帮助。谢谢:)。

【问题讨论】:

  • 您上面的代码会将文本保存在会话中,您所说的保存是什么意思?您在检索值时遇到问题还是要将其保存在持久存储中
  • 你的会议很好
  • @Habib:你最近怎么样?
  • @MartinMulder,不错....??

标签: c# asp.net session save


【解决方案1】:

如果您针对 Button_Click 事件放置代码,那么上面的行 Session["PatientName"] = patientNameTextBox.Text; 将在会话中保存 Text 值。要找回它,您可以这样做:

string patientName = Session["PatientName"] != null ? Session["PatientName"].ToString() 
                                                     : ""; //or null

记住不要在会话中存储太多信息,因为它们是在服务器上为每个用户维护的。

【讨论】:

  • 可以简化为string parientName = Session["PatientName"] ?? "";。也就是说,如果你想首先避免 null。
  • @YoryeNathan,是的,也可以使用空合并运算符。谢谢
  • 顺便说一句,我不确定这是在回答他的问题。现在他有一个变量中的数据,但我感觉他已经知道如何做到这一点(所有的复杂性......) - 他想以某种方式保存它。然而,想要的拯救方式是模糊的。
  • @YoryeNathan,我猜 OP 在检索值时遇到问题,因此说它没有保存。但我会要求澄清
  • 嗨,谢谢你,我现在明白了一点。请问如何将本次会议的信息显示在标签中?
【解决方案2】:

您可以通过以下方式检查该值是否在 Session 内:

if (Session["PatientName"] != null) 
    ...

您可以通过执行以下操作来检索值:

// Remember to cast it to the correct type, because Session only returns objects.
string patientName = (string)Session["PatientName"];

如果你不确定里面是否有值并且你想要一个默认值,试试这个:

// Once again you have to cast. Use operator ?? to optionally use the default value.
string patientName = (string)Session["PatientName"] ?? "MyDefaultPatientName";

将您的答案放回文本框或标签中:

patientLabel.Text = patientName; 

【讨论】:

    【解决方案3】:

    这是在单击按钮时保存会话的方法:

    protected void buttonSaveSession_Click(object sender, EventArgs e)
    {
        string patientName = textBoxPatientName.Text;
        Session["PatientName"] = patientName;
    }
    

    您可以通过以下方式查看或某人有会话:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["PatientName"] != null)
        {
            //Your Method()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 2017-10-20
      • 2017-12-31
      相关资源
      最近更新 更多