ViewState In .NET

The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When an ASP.net page is proceed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field. If the data is too long for a single field then ASP.net performs view state chunking to split it into  multiple hidden fields. The ViewState indicates the status of the page when submitted to the server. 

<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

We can enable ViewState  Encryption to make it difficult for attackers and malicious users to read the ViewState information. To configure ViewState Encryptionfor an application, set the <pagesviewStateEncryptionMode> attribute to Always in the web.config file. Like in the following example:

<configuration>
  <system.web>
    <pages viewStateEncryptionMode="Always" />
  </system.web>
  </configuration>

We can also set the ViewState Encryption for a specific page by setting the value in the page directive:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"  ViewStateEncryptionMode="Always" %>

We can also add and retrieve the data with ViewState like this:

In this example we take a TextBox, Button and a Label in our Web Page:

<asp:TextBox runat="server" id="fname" />
<asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit" />

Name comes from ViewState: <asp:Label runat="server" id="Label1" />

In the .cs Page:

using 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["NameUser"] != null)
Label1.Text = ViewState["NameUser"].ToString();
        else
            Label1.Text = "ViewState Property is not set .";
    }
    protected void SubmitForm_Click(object sender, EventArgs e)
    {
        ViewState["NameUser"] = fname.Text;
     Label1.Text = fname.Text;
    }
}

Ebook Download
View all
Learn
View all