3

我无计可施。我的代码没有跟踪 C# 中的会话

我正在使用应该获取会话数据的用户控件,但它没有。

这是用户控件:

[Serializable]
public partial class studentComments : System.Web.UI.UserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        string currStud;
        if (Session["CS"] == null)
        {
            currStud = "50";
        }
        else
        {
            currStud = (string)Session["CS"];
        }

        lblHeader.Text = "Comments for Student " + currStud;

        //display(currStud);
    }
}

这是初始 aspx.cs 页面中的代码

try
{
    student temp = studList.Find(o => o.student_id == studID);

    Session["CS"] = "45";
    PnlComment.Visible = true;
}
catch (NullReferenceException nre)
{
    lblTest.Text = "Student does not exist!";
}

显然用户控件在 PnlComment 控件中。

编辑 我实际上将一个对象传递给会话,但我将其更改为静态字符串以进行测试,希望这会简化事情。唉,标签一直显示 50。为什么不显示 45?

帮助?

4

2 回答 2

0

It isn't a very widely held opinion but I've always found ASP's session management rules to be a bit counter intuitive so I tend to avoid using them at all. In addition I just don't like using strings as identifiers throughout my program as it can lead to collisions and other sorts of run time bugs.

Stick with using cookies to save your own session identifier that lives in the database and have it serialize/deserialize to an object with properties and fields. It's much more resilient to refactoring and if something goes wrong it's a lot easier to debug.

于 2012-12-03T03:39:16.150 回答
0

您的 default.aspx.cs page_load 事件在用户控件 page_load 事件之后触发,因此虽然页面加载后会话值可能为“45”,但标题文本值将显示旧值“50”,因为它已设置在那之前。

于 2012-12-03T03:50:51.060 回答