Reputation: 390
I'm new to ASP.NET and C#. I have a web form with a static list like this:
private static List<Book> listBook = new List<Book>();
Since the server destroys everything after sending back to client plain HTML, so why whenever I add a new book to the listBook(via checkboxes), it stores info across post back(in a single page)? First I thought it was viewstate but clearly viewstate only stores ASP.NET Control info. Please help me, Thanks in advance!
public partial class TestSortBook : System.Web.UI.Page
{
private static OBMDbContext context = new OBMDbContext();
BookBL bookBL = new BookBL(context);
GenreBL genreBL = new GenreBL(context);
private static List<Genre> listGenre = new List<Genre>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Book> listBook = bookBL.FindAllBooks();
PopulateGridView(listBook);
//PopulateGridView(bookBL.SortBookByPriceAscend(listBook) );
PopulateListView(genreBL.FindAllGenres());
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
HiddenField hf = (HiddenField)cb.FindControl("HiddenField1");
int genreID = Convert.ToInt16(hf.Value);
listGenre.Add(genreBL.FindGenre(genreID));
Response.Write("Nothing");
}
}
Let me explain the code above. There's a listview which has a checkbox and a hidden field in each listview item. Whenever I click a checkbox, it add a new genre to my listGenre
and save info across postback.
Upvotes: 1
Views: 1128
Reputation: 97
Have you considered using the Browser Local storage to store stuff for each user.
depending on what you are storing and how you plan to use it, it might be the best option
Upvotes: 0
Reputation: 15151
where does the static variable store info across postback?
In memory, as any other variable.
You must understand that each page on Asp.net relies in a class, it's not like php or other scripted languages, your site is a program (technically speaking it's an assembly loaded in an AppDomain under the IIS process :P), because that you have an application pool on which you configure how that "program" will run (basically each pool is an isolated AppDomain), so, while the server doesn't purges these application pools your site pages classes will be alive , and thus any static variable will persist on memory.
Upvotes: 0
Reputation: 203804
Since the server destroys everything after sending back to client plain HTML
That's not true at all. Each postback results in a new class instance being created to handle the response for that request. Since you have a static field, its data will persist between requests.
That said, you cannot rely on every single request having access to the same variable with this method; if you have multiple web servers handling responses, they would each have their own static variable. This makes static fields useful for caching content in some instances, but not as the canonical source of data (generally speaking).
Upvotes: 2