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
- protected void BtnSave_Click(object sender, EventArgs e)
- {
- ViewState["UserName"] = txtUserName.Text;
- ViewState["PassWord"] = txtPassword.Text;
- txtUserName.Text = "";
- txtPassword.Text = "";
- }
- protected void BtnRetrive_Click(object sender, EventArgs e)
- {
- if (ViewState["UserName"]!=null&& ViewState["PassWord"] != null)
- {
- txtUserName.Text = ViewState["UserName"].ToString();
- txtPassword.Text = ViewState["PassWord"].ToString();
- }
- }
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- Viewstate is simple. It is used by enabling or disabling the viewstate properties.
- Viewstate doesn't require server resources.
- Viewstate guarantees security since it stores the data in encrypted format.
- It is retained automatically.