类变量损失值 [英] class variable losing value

查看:75
本文介绍了类变量损失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的样子。



我想知道为什么标签中的值为空白或空。



我想在获取数据时将值分配给用户名,并在按钮单击事件中使用它。



有人可以以此为指导我,它为什么会发生以及如何解决此问题



我不想使用会话和静态会话。

 名称空间GUI 
{
公共子类Updatechild:System.Web.UI.Page
{
字符串UserName;

保护无效的Page_Load(对象发送者,EventArgs e)
{
if(!IsPostBack)
{
//调用函数以获取值
GetData();
}
}

protected void GetData()
{
//已分配值VALUE
UserName = USER1
}

//按钮单击事件
受保护的无效Button_Click(对象发送者,EventArgs e)
{
Label.Text = UserName; //值变成空白。
}

}


解决方案

要回答为什么发生这种问题:基本上,每次服务器处理浏览器对该页面的请求时,ASP.NET框架都会为您的 UpdateChild 类。



在您的方案中,发生了2个单独的请求:一个是页面首次加载时,另一个是用户单击按钮时。 p>

在第一个请求期间,由于该请求不是回发,因此您的 UpdateChild 类将值分配给 UserName 变量。但是,由于一旦处理完请求,该 UpdateChild 实例将被丢弃,因此分配给该变量的值将丢失。如果要保留此值,则需要将其存储在页面上类级别变量以外的其他位置。



最简单的解决方案是更改 UserName 类似于以下内容:

 字符串UserName 
{
get {return ViewState [ UserName]作为字符串; }
set {ViewState [ UserName] =值; }
}


This is how my code looks like.

I want to kno why is the value in the label coming as blank or null.

I want to assign the value to username at get data and use it at the button click event.

Can some1 guide me with this and why is it happening and how to solve this issue

I don't want to use a session and static.

namespace GUI
{
  public partial class Updatechild : System.Web.UI.Page
{
    string UserName;

   protected void Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
        {
          //CALL A FUNCTION TO GET THE VALUE
          GetData();
        }
    }

   protected void GetData()
    {
      //VALUE assigned
       UserName= "USER1"
    }

   // button click event
   protected void Button_Click(object sender, EventArgs e)
    {
       Label.Text = UserName; //value comes as blank.
    }

}

解决方案

To answer the question of why this is happening: Basically each time the server handles a request from the browser for that page, the ASP.NET framework creates a new instance of your UpdateChild class.

In your scenario there are 2 separate requests happening: one when the page loads for the first time and another when the user clicks the button.

During the first request, since the request is not a postback, your UpdateChild class assigns a value to the UserName variable. However, since that instance of UpdateChild will be discarded once the request is done processing, the value assigned to that variable is lost. If you want to preserve this value, then you'll need to store it somewhere other than a class-level variable on your page. The most logical place would probably be in either ViewState or Session.

A simple solution to your problem is to change the declaration of UserName to something like the following:

    string UserName
    {
        get { return ViewState["UserName"] as string; }
        set { ViewState["UserName"] = value; }
    }

这篇关于类变量损失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆