The global variable doesn't keep its value

后端 未结 2 1185
感情败类
感情败类 2020-12-20 08:03

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

相关标签:
2条回答
  • 2020-12-20 08:40

    After postbacks the variables lose the value as they are recreated..You can depend HTML hidden inputs..

    Markup:

    <input id="Hidden1" type="hidden"  runat="server"  value=""/>
    

    Code behind:

    Hidden1.value="something";
    
    0 讨论(0)
  • 2020-12-20 08:53

    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.

    0 讨论(0)
提交回复
热议问题