Reputation: 9
Basically I'm trying to use a List<> to store data. I putting the defining part at the top of class(Just after the class is declared). But the problem is that it seems the webpage keeps reloading after I put some data in the list, and so the data keeps getting removed since it's going through the declaration again when it reloads. Is there anyway to define the that the list won't die every time it gets reloaded?
Yeah, I have it defined like this...
public partial class WebForm1 : System.Web.UI.Page
{
DateTime SelectedDate = DateTime.Today;
List<appointment> AppointmentList;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && !IsCallback)
{
AppointmentList = new List<appointment>();
DateTextBox.Text = SelectedDate.ToShortDateString();
for (int x = 0; x <= 23; x++)
{
TimeSpan Hour = new TimeSpan((x * 1), 0, 0);
StartTimeList.Items.Add(Hour.ToString(@"h\:mm"));
EndTimeList.Items.Add(Hour.ToString(@"h\:mm"));
}
}
}
}
Upvotes: 0
Views: 76
Reputation: 148130
Asp.net uses HTTP protocol which is stateless and state is not maintained between http requests. You have to use some technique like ViewState
to maintain the state between requests. You can put the List object in ViewState
and retrieve it from ViewState when you need it.
To Save List<T>
or any object in ViewState
ViewState["YourList"] = list;
To retrieve List<T>
from ViewState
List<YourType> list = (List<YourType>) ViewState["YourList"];
The value of global variables is lost because the Http is a stateless protocol.
A stateless protocol (Http) does not require the HTTP server to retain information or status about each user for the duration of multiple requests. However, some web applications implement states or server side sessions using for instance HTTP cookies or Hidden variables within web forms.
View state is a repository in an ASP.NET page that can store values that have to be retained during postback. The page framework uses view state to persist control settings between postbacks.
You can use view state in your own applications to do the following:
Keep values between postbacks without storing them in session state or in a user profile.
Store the values of page or control properties that you define.
Note: It is not recommended to put large objects in ViewState as it increases the page size and result in increased page access time. ViewState is not encrypted you can encrypt by setting the page's ViewStateEncryptionMode property to true
. You can read Securing View State for more details.
You can also use Session
to store object on Server but if you have large object or large number of client then it can degrade the performance. There you must consider what medium you require. Is it ViewState, Session, Files or DataBase etc.
Upvotes: 3