chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Home ASP.NET State Management in ASP.NET (ViewState, SessionState & ApplicationState)

State Management in ASP.NET (ViewState, SessionState & ApplicationState)

One of the most crucial concepts in Web Development is the State management . In a nutshell, when you request a page from ASP.NET, the Web Server receives it, process it and finally sends the response back to the browser, discarding all the previous Page information. You may ask yourself right now how is then possible to see several server controls, such as TextBox or GridView , maintaining their values during Postbacks. Well, those server controls, use the ViewState Page property to maintain their state. There are three basic objects in ASP.NET to maintain a state in your Page, the ViewState , the SessionState and finally the Application . Each of these are appropriate for different scenarios and this is what we are going to show in this post. We will build a simple Web Application with three Pages and each Web Form will demonstrate one of the three State objects we mentioned. Let’s start.

Open Visual Studio and create an empty ASP.NET Web Application named “StateManagement”. Let us first create the model we are going to use. It will be a simple class named Entry with two properties, “Name” and “EntryEnteredAt”. Create the Entry.cs file inside a folder named “Model”.

namespace StateManagement.Model < [Serializable()] public class Entry < public string Name < get; set; >public DateTime EntryEnteredAt < get; set; >public Entry(string name, DateTime date) < Name = name; EntryEnteredAt = date; >> >

I have made this class Serializable cause we gonna use it in a Repeater control. Now add a WebForm Page and name it ViewState.aspx. Paste the following contents inside the form tag.

 
ViewState Example
Entries Entry Name Created At

Notice that the Repeater’s “ItemType” propety is set to the Entry class we created before. This means that a single row will be generated, displaying the entry name and the time that was created (“EntryEnteredAt”) for each entry object. Now the interesting part. Switch to the code behind file and paste the following code.

public partial class ViewState : System.Web.UI.Page < public static Listentries; protected void Page_Load(object sender, EventArgs e) < if (!IsPostBack) < if (ViewState["entries"] == null) < entries = new List(); entries.Add(new Entry("Entry 1", DateTime.Now)); ViewState["entries"] = entries; bindRepeater(); > else < bindRepeater(); >> > protected void btnAddEntry_Click(object sender, EventArgs e) < ListviewStateEntries = (List)ViewState["entries"]; int entryCounter = viewStateEntries.Count + 1; viewStateEntries.Add(new Entry("Entry " + entryCounter,DateTime.Now)); ViewState["entries"]= viewStateEntries; bindRepeater(); > private void bindRepeater() < Repeater1.DataSource = ViewState["entries"]; Repeater1.DataBind(); >>

Let’s explain a little what we have done here. In the Page_Load event we check if is a postback or not. If it’s not (which means we have a GET request not a PostBack) we check for a ViewState[“entries”] object. If this is null, we initialize a list of Entry objects and add the first Entry. Then we make sure we store this list in the ViewState[“entries”] object. Finally we call the “bindRepeater()” method which reads this ViewState object and binds it’s datasource to it. It’s important to understand that this ViewState object “lives” ONLY for a single Page. Let’s understand what this means by running the application. Set the ViewState Page as the start up page and run it.
stateManagement_01
Click the button a few times to create new entries. In the button click event, we read the ViewState object, add a new Entry and store the entries list again to the ViewState[“entries”]. While at your browser, right click your page and see the source code. You will see a __VIEWSTATE field which is the one that contains all the information stored in the ViewState[“entries”] object.
stateManagement_02
Since this information is maintained at Page level, if you open a new tab (even in the same browser) and request the same ViewState.aspx page, you will see that a new ViewState[“entries”] object will be created, for the new Page. Moreover, if you create a few entries and then click the “Enter” button in the current browser tab, a new Page will be requested again creating once more a new ViewState[“entries”] object. Conclusion? The ViewState object is accessible during PostBacks in the same page only. What if you wanted to access this data from different Pages? This is where the Session object comes to the scene. Create a new WebForm Page named “SessionState.aspx” with the same contents as the ViewState.aspx but in the code behind file replace all the ViewState statements with Session.

public partial class SessionState : System.Web.UI.Page < public static Listentries; protected void Page_Load(object sender, EventArgs e) < if (!IsPostBack) < if (Session["entries"] == null) < entries = new List(); entries.Add(new Entry("Entry 1", DateTime.Now)); Session["entries"] = entries; bindRepeater(); > else < bindRepeater(); >> > protected void btnAddEntry_Click(object sender, EventArgs e) < ListsessionStateEntries = (List)Session["entries"]; int entryCounter = sessionStateEntries.Count + 1; sessionStateEntries.Add(new Entry("Entry " + entryCounter, DateTime.Now)); Session["entries"] = sessionStateEntries; bindRepeater(); > private void bindRepeater() < Repeater1.DataSource = Session["entries"]; Repeater1.DataBind(); >>

Select this new Page as the start up page and run your application. Create a few Entries by clicking the button. Then request the same page in a different tab on the same browser or if you wish, open a new instance of the same browser and request the page as follow.
stateManagement_03
The main difference between the Session and the ViewState is that Session state is maintained at the server, not in the Page. This makes the Session state available to different pages but in the same session. In explanation, try to create some entries in IE and then request the same page in another browser, e.g Firefox. The Session[“entries”] will be null in Firefox which means this is a new Session. If you want to check when exactly a Session is created, add a Global.asax file in your application and add a breakpoint in the Session_Start event. Then run your application in debug mode..
stateManagement_04
Generally speaking, you use the Session to keep state for different users. If you want to store some information and make it accessible to all users, from many pages even from different Sessions, then you use the Application object. Create a new WebForm page named “ApplicationState” with the same HTML data as the “SessionState.aspx”. In the code behind file replace all the “Session” statements with Application.

public partial class ApplicationState : System.Web.UI.Page < public static Listentries; protected void Page_Load(object sender, EventArgs e) < if (!IsPostBack) < if (Application["entries"] == null) < entries = new List(); entries.Add(new Entry("Entry 1", DateTime.Now)); Application["entries"] = entries; bindRepeater(); > else < bindRepeater(); >> > protected void btnAddEntry_Click(object sender, EventArgs e) < ListapplicationStateEntries = (List)Application["entries"]; int entryCounter = applicationStateEntries.Count + 1; applicationStateEntries.Add(new Entry("Entry " + entryCounter, DateTime.Now)); Application["entries"] = applicationStateEntries; bindRepeater(); > private void bindRepeater() < Repeater1.DataSource = Application["entries"]; Repeater1.DataBind(); >>

stateManagement_05

Now repeat the scenario where you create some entries in IE and then request the same page in a different browser. You will notice that the Application[“entries”] is accessible even from different sessions.

That’s it, I hope you have understood the differences between ViewState, Session and Application State objects in ASP.NET. Download the project we created from here. Make sure you follow this blog to keep notified for new posts!