全局变量不保留其值 [英] The global variable doesn't keep its value

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

问题描述

问题是,每次执行回发操作时,变量值"都不会保持其先前的值,并且字典始终为空.它没有任何先前保存的数据.如何保存数据?

The problem is , every time i do a postback my variable "value" doesn't keep it's previous value, and always the dictionary is empty. It doesn't have any previous saved data. How can i make it to save data ?

这是代码:

public partial class MyCart : System.Web.UI.Page
        {
            public Dictionary<string, string> value = new Dictionary<string, string>();
            protected void Page_Load(object sender, EventArgs e)
            {
                    TextBox textbox = new TextBox();                
                    textbox.TextChanged += textbox_TextChanged;
                    textbox.ID = "textbox" + p.IDProduct.ToString();
                    Button button = new Button();
            }

            void textbox_TextChanged(object sender, EventArgs e)
            {
                   value.Add(((TextBox)sender).ID, ((TextBox)sender).Text);
            }
}

推荐答案

global变量是在 Postback 上重新创建的,您可能需要将变量放在ViewState中,以使其在两次回发之间保持数据.

The global variable are recreated on Postback you probably need to put the variable in ViewState for keep its data between postbacks.

如果数据很小,用ViewState就可以了,但是如果数据很大,则可能需要考虑另一种存储介质可以是数据库.

If data is small the its fine with ViewState but if data is large then your might need to think an alternative medium of storage could be database.

要使用ViewState进行操作,您将需要类似的东西.

To do it with ViewState you would need something like.

public Dictionary<string, string> value = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{

     if(ViewState["valDic"] != null)
         value = (Dictionary<string, string>)ViewState["valDic"];
     TextBox textbox = new TextBox();                
     textbox.TextChanged += textbox_TextChanged;
     textbox.ID = "textbox" + p.IDProduct.ToString();
     Button button = new Button();
}   

void textbox_TextChanged(object sender, EventArgs e)
{
     value.Add(((TextBox)sender).ID, ((TextBox)sender).Text);
     ViewState["valDic"] = value;
}

视图状态是ASP.NET页面框架用于执行以下操作的方法 保留往返之间的页面和控制值.当HTML 呈现页面的标记,页面的当前状态和 回发期间必须保留的值被序列化为 base64编码的字符串.然后将此信息放入视图 状态隐藏字段,请 MSDN .

View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view state hidden field or fields, MSDN.

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

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