Thursday, October 4, 2018

What is Session and View state in asp.net c#

Various state management techniques

A. Client-side State Management: 
  • View State
  • Hidden Field
  • Cookies
  • Control State
B. Server-side State Management
  • Session
  • Application Object
  • Caching


1. View state 

View State is a technique to maintain the state of controls during page post-back, meaning it stores the page value at the time of post-back (sending and receiving information from the server) of your page and the view state data can be used when the page is posted back to the server and a new instance of the page is created.


Sample Code 

  1. namespace Test  
  2. {  
  3.     public partial class _Default : Page  
  4.     {  
  5.         int TestCounter = 0;  
  6.         protected void Page_Load(object sender, EventArgs e)  
  7.         {  
  8.             if(!IsPostBack)  
  9.             {  
  10.                 TextBox1.Text = "0";  
  11.                 TextBox2.Text = "0";  
  12.             }  
  13.         }  
  14.         protected void Button1_Click(object sender, EventArgs e)  
  15.         {  
  16.             //With out View State  
  17.             TestCounter = TestCounter + 1;  
  18.             TextBox1.Text = TestCounter.ToString();  
  19.   
  20.             if (ViewState["counter"] != null)  
  21.             {  
  22.                 TestCounter = (int)ViewState["counter"] + 1;  
  23.                 TextBox2.Text = TestCounter.ToString();  
  24.             }  
  25.             ViewState["counter"] = TestCounter;  
  26.   
  27.         }  
  28.     }  
  29. }  


View State advantages: 
  • Very easy to implement.
  • Stored on the client browser in a hidden field as a form of Base64 Encoding String not encrypted and can be decoded easily.
  • Good with HTTP data transfer
View State disadvantages:
  • The performance overhead for the page is larger data stored in the view state.
  • Stored as encoded and not very safe to use with sensitive information.

Session State :-

in session state one we stored value in session then we can use it on another page but in view state we can not use stored value on another page.


  1. //Stored Textbox value  
  2. Session["Counter"] = TextBox3.Text;  
  3.   
  4. //Stored Dataset  
  5.    
  6. Session["ds"] = dsData;  
  7. Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property.  




0 Comments:

Post a Comment

JOIN US ON TELEGRAM