ASP.net C # Saving Postback List

My situation is as follows: I have these lists with data inserted into them when the user presses the ADD button, but I think that after the postback, the lists are reset again. How do you save them? I was looking for an answer, but I think I do not quite understand how to use a session, etc.

I am very new to ASP.net and not much better with C #. It would seem that.

public partial class Main : System.Web.UI.Page { List<string> code = new List<string>(); protected void Page_Load(object sender, EventArgs e) { //bleh } protected void cmdAdd_Click(object sender, EventArgs e) { code.Add(lstCode.Text); } 
+6
source share
3 answers

Just use this property to store information:

 public List<string> Code { get { if(HttpContext.Current.Session["Code"] == null) { HttpContext.Current.Session["Code"] = new List<string>(); } return HttpContext.Current.Session["Code"] as List<string>; } set { HttpContext.Current.Session["Code"] = value; } } 
+14
source

This is weird in ASP.NET. Whenever you programmatically add items to a collection control (listbox, combobox), you must re-populate the control with each postback.

This is because ViewState only knows the elements added during the page rendering cycle. Adding items on the client side only works for the first time, after which the item is gone.

Try the following:

 public partial class Main : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["MyList"] = new List<string>(); } ComboBox cbo = myComboBox; //this is the combobox in your page cbo.DataSource = (List<string>)Session["MyList"]; cbo.DataBind(); } protected void cmdAdd_Click(object sender, EventArgs e) { List<string> code = Session["MyList"]; code.Add(lstCode.Text); Session["MyList"] = code; myComboBox.DataSource = code; myComboBox.DataBind(); } } 
+3
source

You cannot save values ​​between feedback messages.

You can use a session to save the list:

 // store the list in the session List<string> code=new List<string>(); protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) Session["codeList"]=code; } // use the list void fn() { code=List<string>(Session["codeList"]); // downcast to List<string> code.Add("some string"); // insert in the list Session["codeList"]=code; // save it again } 
+1
source

Source: https://habr.com/ru/post/913976/


All Articles