Session对象不更新ASP.NET对象、Session、NET、ASP

2023-09-04 08:39:05 作者:灵魂狗友i

我在code设置会话对象在一个关键时刻:

I set a session object at one juncture in my code:

Session("my_name") = "Dave"

后来在我的code我给用户一个机会来更新这个对象:

Later in my code I give the user a chance to update this object:

Session("my_name") = TextBox1.Text

我重装我的网页,并显示像这样你好一点的语句:

I reload my page and display a little hello statement like this:

Label1.Text = "Hello" & CStr(Session("my_name"))

的结果是:你好戴夫不管我怎么改变会议(MY_NAME)太

The result is: "Hello Dave" no matter what I change Session("my_name") too.

编辑:这是一个完整的code-后面我写了要证明:

Here is the a full code-behind I wrote up to demonstrated:

Public Class WebForm1
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.ExpiresAbsolute = DateTime.Now.AddMonths(-1)
    If Page.IsPostBack = False Then
        Session("my_name") = "Dave"
    End If
    Label1.Text = CStr(Session("my_name"))
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
    Session("my_name") = TextBox1.Text
End Sub

末级

推荐答案

加载事件触发达越快比按钮的click事件。因此,在它运行的时候,会话的值(MY_NAME)仍是戴夫。

The Page's Load event fires up sooner than the Button's click event. Therefore, at the time it runs, the value of Session("my_name") is still "Dave".

如果你想正确设置它,你要么把 Label1.Text = CStr的(会话(MY_NAME)) preRender 活动页面的处理程序。

If you'd like to set it up correctly, you should either put the Label1.Text = CStr(Session("my_name")) into the PreRender event handler of your page.

您剪切把它放到按钮的点击事件以及(设置会话值后,当然),但我想,你以后要使用的会话存储对象为没有价值的目的。

You cut put it into the Button's Click event as well (after setting the session value, of course), but I guess that you want to use the session later for storing objects for less trivial purposes.

(我猜你想使用会话更先进的目的后。毕竟,这将是使用会话,如果你只是想更改标签的文本的点?)

(I guess that you'd like to use the session for more advanced purposes later. After all, what would be the point of using session if you only want to change a label's text?)

基本上,这里是你想要的:

Basically, here is what you want:

在Page_Load设置会议(MY_NAME),以戴夫,如果它不是一个回发 在Button1_Click的设置会议(MY_NAME)的文本框的文本 的PAGE_ preRender设置标签的文本。

下面是正在发生的事情与你目前的code:

Here's what's happening with your current code:

在Page_Load设置会议(MY_NAME),以戴夫,如果它不是一个回发 在Page_Load设置标签的文本 在Button1_Click的设置会议(MY_NAME)的文本框的文本

您可以阅读更多关于该话题在这里: ASP.NET页面生命周期概述。

You can read more about the topic in here: ASP.NET Page Life Cycle Overview.