我的 ViewState 有问题

发布于 2024-11-16 06:32:02 字数 511 浏览 5 评论 0原文

我这样使用视图状态:

public bool SearchClicked 
{ 
    get { return  Session["bool"]==null? false : (bool)Session["Bool"]; } 
    set { Session["bool"] = value; } 
}

在代码中,每当按下按钮时,就会触发事件。

我设置它:

    SearchClicked=true;

每次回发时,我都会检查它是否为真:

 if (SearchClicked)
{
}

当我启动站点并且有回发时,该值设置为“true”。

确实,当我运行应用程序时,我按下了几次将其设置为 true 的按钮。但每次运行应用程序时,应用程序实例都是新的。这是否意味着 ViewState 会在每次运行应用程序时重置自身,并且不会像会话(20 分钟)那样保存其状态?

I use viewstate like this:

public bool SearchClicked 
{ 
    get { return  Session["bool"]==null? false : (bool)Session["Bool"]; } 
    set { Session["bool"] = value; } 
}

In The code whenever the button pressed, the events triggered.

I set it:

    SearchClicked=true;

With every post back I check if it is true or not:

 if (SearchClicked)
{
}

When I start the site and there is a postback, the value is set to "true".

It is true that i pressed the button that set it to true a few times before when i run the application. But the application instance is new everytime I run the application. Doesnt it mean that the ViewState resets itself with every time I run the application and doesnt save its state like Session (20mins)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心在旅行 2024-11-23 06:32:02

在上面的代码中,您没有使用 ViewState 来存储 SearchClicked 值,而是使用 Session 来存储它。 ViewState 以隐藏值的形式保留在页面上,并发布回服务器。这意味着视图状态存储在浏览器上,因此只要用户在页面上,视图状态就会持续存在。会话信息存储在服务器上。用户会话最终会超时,但其他事情可能会导致会话重置,例如重建应用程序或编辑 web.config 文件。

要存储到 ViewState,请使用以下命令

public bool SearchClicked
{
get { return  ViewState["bool"] == null ? false : (bool)ViewState["bool"]; }
set { ViewState["bool"] = value; }
}

In your code above, you are not using ViewState to store the SearchClicked value, but rather you are using the Session to store it. ViewState is persisted on the page in a hidden value and gets posted back to the server. This means that the viewstate is stored on the browser, and therefor will persist as long as the user is on the page. Session information is stored on the server. A users session will eventually time out, but other things can cause the session to reset, such as rebuilding the application or editing the web.config file.

To store to ViewState use the following

public bool SearchClicked
{
get { return  ViewState["bool"] == null ? false : (bool)ViewState["bool"]; }
set { ViewState["bool"] = value; }
}
爱她像谁 2024-11-23 06:32:02

视图状态处理回发时页面的“状态”,仅此而已。它实际上与应用程序关系不大;其目的很简单。

我发现这篇文章对我早期的 .NET 学习非常有帮助:
了解 ASP.NET 视图状态
(特别是“视图状态的作用”部分)

The viewstate handles the "state" of the page when posting back, nothing more or less. It really has little to do with the application; It's purpose is simple.

I found this article very helpful earlier in my .NET learning:
Understanding ASP.NET View State
(Particularly section "The Role of View State")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文