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.

<form id="form1" runat="server">
        <div>
            <span style="color: red; font-size: large">ViewState Example</span>
            <fieldset style="background-color: ghostwhite;width:283px">
                <legend>Entries</legend>
                <table>
                    <tr>
                        <th>Entry Name</th>
                        <th>Created At</th>
                    </tr>
                    <asp:Repeater ID="Repeater1" runat="server" ItemType="StateManagement.Model.Entry">
                        <ItemTemplate>
                            <tr>
                                <td><%# Eval("Name") %></td>
                                <td><%# Eval("EntryEnteredAt") %></td>
                            </tr>

                        </ItemTemplate>
                    </asp:Repeater>
                </table>
                <br />
                <asp:Button ID="btnAddEntry" runat="server" Text="Add New Entry" OnClick="btnAddEntry_Click" />
            </fieldset>
        </div>
    </form>

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 List<Entry> entries;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (ViewState["entries"] == null)
                {
                    entries = new List<Entry>();
                    entries.Add(new Entry("Entry 1", DateTime.Now));
                    ViewState["entries"] = entries;
                    bindRepeater();
                }
                else
                {
                    bindRepeater();
                }
            }
        }

        protected void btnAddEntry_Click(object sender, EventArgs e)
        {
            List<Entry> viewStateEntries = (List<Entry>)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 List<Entry> entries;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["entries"] == null)
                {
                    entries = new List<Entry>();
                    entries.Add(new Entry("Entry 1", DateTime.Now));
                    Session["entries"] = entries;
                    bindRepeater();
                }
                else
                {
                    bindRepeater();
                }
            }
        }

        protected void btnAddEntry_Click(object sender, EventArgs e)
        {
            List<Entry> sessionStateEntries = (List<Entry>)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 List<Entry> entries;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Application["entries"] == null)
                {
                    entries = new List<Entry>();
                    entries.Add(new Entry("Entry 1", DateTime.Now));
                    Application["entries"] = entries;
                    bindRepeater();
                }
                else
                {
                    bindRepeater();
                }
            }
        }

        protected void btnAddEntry_Click(object sender, EventArgs e)
        {
            List<Entry> applicationStateEntries = (List<Entry>)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();
        }
    }

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.
stateManagement_05
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!

Advertisements


Categories: ASP.NET

Tags: , , , ,

1 reply

  1. Nice and simple explanation of the ViewState, SessionState and ApplicationState. Thanks and keep them coming.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Diary Of A Programmer

Because every day is worth noting

Chara Plessa

The purpose of this blog is to broaden my education, promote experimentation and enhance my professional development. Albert Einstein once said that “If you can’t explain it simply, you don’t understand it well enough” and I strongly believe him!

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Kumikoro

A Front End Developer's Blog

Muhammad Hassan

Full Stack Developer | ASP.NET | MVC | WebAPI | Advanced Javascript | AngularJS | Angular2 | C# | ES6 | SQL | TypeScript | HTML5 | NodeJS, MS candidate @LUMS, Grad & EX-Adjunct Faculty @NUCES-FAST, seasonal blogger & open-source contributor. Seattle, WA.

Software Engineering

Web development

IEvangelist

.NET, ASP.NET, C#, MVC, TypeScript, AngularJS

leastprivilege.com

Dominick Baier on Identity & Access Control

Happy DotNetting

In Love with Technology

Knoldus

Knols of experience to your advantage

knowshnet

Search - Read - Request - Share

Rahul's space

Learn, Share and Grow with me !

Dhananjay Kumar

Developer Evangelist @Infragistics | MVP @Microsoft |

SQL Authority with Pinal Dave

SQL Server Performance Tuning Expert

Conficient Blog

Random bits of tech from @conficient

Code! Code! Code!

SOLID & KISS

Code Wala

Designing and coding

Microsoft Mentalist

A way to start with Microsoft Technologies

Tony Sneed's Blog

A glimpse into the lives of Tony & Zuzana Sneed

%d bloggers like this: