ViewState Explained in ASP.NET

Introduction
 
In this blog, I will explain viewstate in ASP.NET. Viewstate is used to store the state of server-side controls between the postback of the webpage. It stores the data within the same page (in encrypted format), while the session state is stored in the server. The information is stored in HTML hidden fields. Viewstate is used by enabling or disabling the viewstate properties. It is default for viewstate to be true, but you can disable it by setting the EnableViewState property to false.
 
Example
 
WebForm.aspx.cs 
  1. protected void BtnSave_Click(object sender, EventArgs e)  
  2. {  
  3. ViewState["UserName"] = txtUserName.Text;  
  4. ViewState["PassWord"] = txtPassword.Text;  
  5. txtUserName.Text = "";  
  6. txtPassword.Text = "";  
  7. }  
  8. protected void BtnRetrive_Click(object sender, EventArgs e)  
  9. {  
  10. if (ViewState["UserName"]!=null&& ViewState["PassWord"] != null)  
  11. {  
  12. txtUserName.Text = ViewState["UserName"].ToString();  
  13. txtPassword.Text = ViewState["PassWord"].ToString();  
  14. }  
  15. }  
Output
 
Step 1
 
Click the save button and the value of the username and password is submitted in viewstate, which has the value of username and password during postback.
 
 
Step 2
 
Click the retrieve button so we can get the stored value. The value must be retained during postback and this information is stored in HTML hidden fields.
 
Advantages
  1. Viewstate is simple. It is used by enabling or disabling the viewstate properties.
  2. Viewstate doesn't require server resources.
  3. Viewstate guarantees security since it stores the data in encrypted format.
  4. It is retained automatically.