gpt4 book ai didi

c# - 为什么我的 bool 变量的值在回发之间丢失

转载 作者:太空狗 更新时间:2023-10-29 22:06:38 26 4
gpt4 key购买 nike

我有一个名为 CheckBoxActivated 的 bool 变量,我在验证用户名和密码后将其分配给 true。

string name = us.UserName;
string password = us.Password;

if (name.Equals(txtName.Text) && (password.Equals(txtPassword.Text)))
{
CheckBoxAvtivated = true;

奇怪的是,在将“true”分配给变量后,我单击另一个按钮,它立即变为“false”,这会导致不良行为。

protected void butNext_Click(object sender, EventArgs e)
{
if (CheckBoxAvtivated)
{
pnlCheckBoxes.Visible = true;
pnlUserCheckBoxValidation.Visible = false;
}
else
{
pnlCheckBoxes.Visible = false;
pnlUserCheckBoxValidation.Visible = true;
}

变量的状态因此意外地变为 false。为什么会发生这种情况?

最佳答案

asp.net 中的类级别变量(全局变量)不会在回发之间保持状态,如果要在回发之间保持状态,则必须使用 viewstate。 ASP.NET 基于 HTTP 协议(protocol),该协议(protocol)是无状态协议(protocol),不提供在请求之间存储用户数据的方法

在viewstate中设置

ViewState["CheckBoxAvtivated"] = "true";

从viewstate获取

bool CheckBoxAvtivated = bool.Parse(ViewState["CheckBoxAvtivated"].ToString());

了解在何处使用 View 状态以及在何处不应使用 View 状态非常重要。

View 状态的作用

View state's purpose in life is simple: it's there to persist stateacross postbacks. (For an ASP.NET Web page, its state is the propertyvalues of the controls that make up its control hierarchy.) This begsthe question, "What sort of state needs to be persisted?" To answerthat question, let's start by looking at what state doesn't need to bepersisted across postbacks. Recall that in the instantiation stage ofthe page life cycle, the control hierarchy is created and thoseproperties that are specified in the declarative syntax are assigned.Since these declarative properties are automatically reassigned oneach postback when the control hierarchy is constructed, there's noneed to store these property values in the view state.

来自 MSDN .

无状态协议(protocol)

In computing, a stateless protocol is a communications protocol thattreats each request as an independent transaction that is unrelated toany previous request so that the communication consists of independentpairs of requests and responses. A stateless protocol does not requirethe server to retain session information or status about eachcommunications partner for the duration of multiple requests. Incontrast, a protocol which requires the keeping of internal state isknown as a stateful protocol.

来自 Wikipedia

关于c# - 为什么我的 bool 变量的值在回发之间丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14619476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com