-
It’s of type StateBag and is used for storing state/data to be used in postback to the same web form.
-
ViewState being hidden element in form tag rendered, its different for different clients & is submitted to the server only if the form is submitted or posted.
-
ViewState is a collection of Key-Value pairs, where Key is of type String and Value is of type Object. But only those objects which are marked as Serializable can be stored in ViewState.
-
ViewState cannot be programmed on the client in javascript because the value of it is encrypted before it is rendered to the browser.
-
If ViewState of the page is disabled (<%@Page EnableViewState=”False”) than anything added to it is not retained.
Example:1
12345678910111213141516<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title>ViewState</title></head><body><form id="form1" runat="server"><asp:TextBox runat="server" id="NameField" /><asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" /><asp:Button runat="server" id="RefreshPage" text="Just submit" /><br /><br />Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" /></form></body></html>And the Code Behind:
1234567891011121314151617181920using System;using System.Data;using System.Web;public partial class _Default : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if(ViewState["NameOfUser"] != null)NameLabel.Text = ViewState["NameOfUser"].ToString();elseNameLabel.Text = "Not set yet...";}protected void SubmitForm_Click(object sender, EventArgs e){ViewState["NameOfUser"] = NameField.Text;NameLabel.Text = NameField.Text;}}
Example:2
12345678910111213141516<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"><title>ViewState</title></head><body><form id="form1" runat="server"><asp:Button ID=” runat=” Text=” OnClick=”btnNew_Click” /><asp:Button ID=” runat=” Text=” OnClick=”bnEdit_Click” /><asp:Button ID=” runat=” Text=” visible=” OnClick=”btnSave_Click” /><br /><br />Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" /></form></body></html>
And the Code Behind:
123456789101112131415161718192021222324252627282930313233343536protected void btnNew_Click(. . .){btnNew.Visible = false;btnEdit.Visible = false;btnSave.Visible = true;ViewState[“state”] = “new”;}protected void bnEdit_Click(. . .){btnNew.Visible = false;btnEdit.Visible = false;btnSave.Visible = true;ViewState[“state”] = “edit”;}protected void btnSave_Click(. . .){if (ViewState[“state”].ToString() == “new”)Response.Write(“New record );elseResponse.Write(“Existing record );}