Difference between ViewState, Session State and Application State in asp.net - Part 5

Suggested videos before continuing with this session
Part 3 - View State in ASP.NET
Part 4 - Events in the life cycle of a web application

Let's understand the differences, with an example. Create a new asp.net web application. 

ViewState:
Add a new WebForm, to the project and name it ViewState1.aspx. Drag and drop a button and a text box control onto the webform. Double click the button control on the webform. This automatically generates the event handler, for the button control. 

Now add another webform, to the project, with name ViewState2.aspx. Just like you have done for ViewState1.aspx, drag and drop a TextBox and a Button control onto this webform as well. 

Now, copy and paste the following code in ViewState1.aspx.cs and ViewState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (ViewState["Clicks"] == null)
        {
            ViewState["Clicks"] = 0;
        }
        TextBox1.Text = ViewState["Clicks"].ToString();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    int ClicksCount = (int)ViewState["Clicks"] + 1;
    TextBox1.Text = ClicksCount.ToString();
    ViewState["Clicks"] = ClicksCount;
}

Now, run the application, and navigate to ViewState1.aspx. Click the button control. Everytime, you click the button, the clicks count get incremented and is displayed in the TextBox, as expected.

Now, navigate to ViewState2.aspx. Click the button, on this page. Notice, that the value starts from ZERO, indicating that, each page has it's own ViewState["Clicks"].

So, the conclusion is that, ViewState of a webform is available only with in that webform, by default.

So, where does this viewstate, gets stored - On the client or on the server? ViewState is stored on the page using a hidden field called _ViewState. So, ViewState travels along with the page, between the client and the server, with each request and response. 

ASP.NET uses viewstate, to retain the values a user types into controls on the webform, across postbacks.



SessionState:
Add a new webform with name SessionState1.aspx. Drag and drop a button and a text box control onto SessionState1.aspx. Do the same thing by adding a page with name SessionState2.aspx.

Copy and paste the following code in SessionState1.aspx.cs and SessionState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Session["Clicks"] == null)
        {
            Session["Clicks"] = 0;
        }
        TextBox1.Text = Session["Clicks"].ToString();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    int ClicksCount = (int)Session["Clicks"] + 1;
    TextBox1.Text = ClicksCount.ToString();
    Session["Clicks"] = ClicksCount;
}

Add the following sessionstate element to your web.config file, under system.web. This setting, specifies the web application to use cookieless sessions.
<sessionState mode="InProc" cookieless="true"></sessionState>

Run the application and navigate to SessionState1.aspx. Click the button 3 times, and notice that, the value 3 is displayed in the TextBox. Now, navigate to SessionState2.aspx. The value 3 is displayed in the TextBox on SessionState2.aspx. Now, click twice, the value is incremented to 5. Now, navigate back to SessionState1.aspx, and you should see the value 5. This proves that a session state variable is accessible across all pages in a web application. 

Now, open a new browser window and navigate to SessionState1.aspx (Make sure you have a different session-id). Notice that, the value in the textbox is ZERO. So, this proves that, Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data. Only the current session has access to its Session state.



Application State:
Add a new webform with name ApplicationState1.aspx. Drag and drop a button and a text box control onto ApplicationState1.aspx. Do the same thing by adding a page with name ApplicationState2.aspx.

Copy and paste the following code in ApplicationState1.aspx.cs and ApplicationState2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        if (Application["Clicks"] == null)
        {
            Application["Clicks"] = 0;
        }
        TextBox1.Text = Application["Clicks"].ToString();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    int ClicksCount = (int)Application["Clicks"] + 1;
    TextBox1.Text = ClicksCount.ToString();
    Application["Clicks"] = ClicksCount;
}

Run the application and navigate to ApplicationState1.aspx. Click the button 3 times, and notice that, the value 3 is displayed in the TextBox. Now, navigate to ApplicationState2.aspx. The value 3 is displayed in the TextBox on ApplicationState2.aspx. Now, click twice, the value is incremented to 5. Now, navigate back to ApplicationState1.aspx, and you should see the value 5. This proves that an application state variable is accessible across all pages in a web application. 

Now, open a new browser window and navigate to ApplicationState1.aspx. Notice that, the value in the textbox is still 5. So, this proves that, Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data. All sessions can read and write Application State variables.

So, in short, the differences are as follows
ViewState:
1. ViewState of a webform is available only with in that webform
2. ViewState is stored on the page in a hidden field called _ViewState. Because of this, the ViewState, will be lost, if you navigate awaya from the page, or if the broswer is closed.
3. ViewState is used by all asp.net controls to retain their state across postback

Session State:
1. Session state variables are available across all pages, but only for a given single session. Session variables are like single-user global data.
2. Session state variables are stored on the web server.
3. SessionState variables are cleared, when the user session times out. The default is 20 minutes. This is configurable in web.config

Application State:
1. Application State variables are available across all pages and across all sessions. Application State variables are like multi-user global data.
2. Application State variables are stored on the web server.
3. Application State variables are cleared, when the process hosting the application is restarted.

13 comments:

  1. Very nice explanations! Even for someone like me who is reading it for the first time as skill acquisition.

    ReplyDelete
  2. Hello Venkat Sir...

    Thankzz A lot For Your Free Tutorials...

    The way of Presentation is very nice and Understandable...

    I Wish You From The Bottom of Heart, From Lord of The Universe That..."All Your Good Wishes Come true".

    ReplyDelete
  3. Thank you for sharing the tutorials. Excellent teaching!!!

    ReplyDelete
  4. Thanks venkat thank you so much for this knowledge sharing
    i am your big fan...

    ReplyDelete
  5. superb...Actually i didnt understand session concept from last 2 months. studying on this material i really trully understand all concept in only half hours. thank u pragim for your great support.
    thank u so much.

    ReplyDelete
  6. thanks a lot sir for such a nice explanation..

    ReplyDelete
  7. Thank you for sharing the tutorials. Excellent teaching!!!

    ReplyDelete
  8. Sir, when i tried with this example
    for session state and application state
    even if i refresh the page also the value is incrementing
    how this is possible, please reply on this

    ReplyDelete
  9. Refreshing the Page does not ends the session. Closing the browser does.

    ReplyDelete
  10. Sir, I want to display .csv file contents in a excel sheet. Then, how it can be done? Kindly guide.

    ReplyDelete
  11. thank you very much sir.....i did not understand the....the session concept from last 1 month....but your explaination is very easy to understand...again thank you very much sir..for this

    ReplyDelete
  12. Nothing equal to donating knowledge to people. you done it sir. Millions get benefited from your tutorial. God bless you and your family for generations sir. You will be in our prayers everyday.

    ReplyDelete
  13. Thank you for sharing the tutorials. Excellent teaching!!!
    Lord of The Universe That..."All Your Good Wishes Come true".

    ReplyDelete

It would be great if you can help share these free resources