Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

asp.net - The global variable doesn't keep its value

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 ?

this is the code :

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);
            }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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;
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...