Introduction
A web application is stateless. That means that a new instance of a page is created every time we make a request to the server to get the page, and after the round trip, our page is lost immediately. It only happens because of one server, all the controls of the Web Page are created, and after the round trip, the server destroys all the instances. So to retain the values of the controls we use state management techniques.
State Management Techniques
They are classified into the following 2 categories.
What is View State?
View State is the method to preserve the Value of the Page and Controls between round trips. It is a Page-Level State Management technique. View State is turned on by default and normally serializes the data in every control on the page regardless of whether it is actually used during a post-back.
Now I am showing you an example of what the problem is when we don't use view state.
Step 1. Open Visual Studio 2010.
Step 2. Then click on "New Project" > "Web" >"ASP.NET Empty Web Application."
Step 3. Now click on Solution Explorer.
Step 4. Now right-click on the "ADD" > "New Item" > "Web Form" and add the name of the Web Form just like I did in WebForm6.aspx.
Step 5. After adding the WebForm6.aspx you will see the following code.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm6.aspx.cs" Inherits="view_state.WebForm6" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>
UserName: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Password: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="Restore" />
</p>
</form>
</body>
</html>
Now write the code as in the following.
// Declaration of 'a' and 'b'
public string a, b;
protected void Button1_Click(object sender, EventArgs e)
{
// TextBox1 and TextBox2 values are assigned to the variables 'a' and 'b'
a = TextBox1.Text;
b = TextBox2.Text;
// After clicking on Button, TextBox values will be cleared
TextBox1.Text = TextBox2.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
// Values of variables 'a' and 'b' are assigned to TextBox1 and TextBox2
TextBox1.Text = a;
TextBox2.Text = b;
}
Output
It only happens because all the controls are classes and on the server, all the Control Objects are created and then after the round trip, the Page is returned to the client's browser in HTML format, and the objects are destroyed at the server.
After the Submit button is clicked, the value of the user name and password is submitted to the server. We cannot restore the value again because after the postback, the instance of the control is destroyed, and on clicking the Restore Button, the server takes a new request, and the server cannot restore the value of the TextBox.
Features Of View State
These are the main features of the view state.
- Retains the value of the Control after post-back without using a session.
- Stores the value of Pages and Control Properties defined in the page.
- Creates a custom View State Provider that lets you store View State Information in a SQL Server Database or in another data store.
Now, I am explaining the stored value in the View State, and the remaining steps are the same as the previous ones.
Now write this code.
protected void Button1_Click(object sender, EventArgs e)
{
// Value of TextBox1 and TextBox2 is assigned to the ViewState
ViewState["name"] = TextBox1.Text;
ViewState["password"] = TextBox2.Text;
// After clicking on Button, TextBox value will be cleared
TextBox1.Text = TextBox2.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
// If ViewState values are not null, assign them to TextBoxes
if (ViewState["name"] != null)
{
TextBox1.Text = ViewState["name"].ToString();
}
if (ViewState["password"] != null)
{
TextBox2.Text = ViewState["password"].ToString();
}
}
Output
After clicking on the Submit Button, the value of the user name and password is submitted in View State, and the View State stores the value of the user name and password during post-back.
After clicking on the Restore Button, we can get the value again. The Value must be retained during post-back, and the values are stored into a base 64 encoded string, and this information is then put into the View State Hidden Field.
Data Objects That Can be Stored in View state
- String
- Boolean Value
- Array Object
- Array List Object
- Hash Table
- Custom type Converters
Advantages of View State
- Easy to Implement.
- No server resources are required: The View State is contained in a structure within the page load.
- Enhanced security features: It can be encoded and compressed or Unicode implementation.
Disadvantages of View State
- Security Risk: The Information of View State can be seen in the page output source directly. You can manually encrypt and decrypt the contents of a Hidden Field, but It requires extra coding. If security is a concern then consider using a Server-Based state Mechanism so that no sensitive information is sent to the client.
- Performance: Performance is not good if we use a large amount of data because View State is stored in the page itself and storing a large value can cause the page to be slow.
- Device limitation: Mobile Devices might not have the memory capacity to store a large amount of View State data.
- It can store values for the same page only.
When We Should Use View State
- When the data to be stored is small.
- Try to avoid secure data.
How to Enable and Disable View State
You can enable and disable View State for a single control as well as at the page level. To turn off View State for a single control, set the EnableViewState property of that control to false.
TextBox1.EnableViewState=false;
To turn off the View State for an entire page, we need to setEnableViewState to false of the page directive, as shown below.
<%PageLanguage="C#"EnableViewState="false";
To enable the same, you need to use the same property just set it to "True".
View State Security
View State Data is stored in the form of Base 64 encoding, but it is not very secure. Anyone can easily break it. So there are the following 2 options,
- Using the MAC for Computing the View State Hash Value
Generally, the larger MAC key is used to generate a Hash Key. When the key is auto-generated, then ASP.NET uses SHA-1 encoding to create a larger key. Those keys must be the same for all the servers. If the key is not the same and the page is posted back to a different server than the one that created the page, then the ASP.NET Page Framework raises an exception. We can enable it by using.
<%PageLanguage="C#"EnableViewState="true"EnableViewStateMac="true";
- Encryption
By using MAC Encoding, we cannot prevent the viewing of the data, so to prevent the viewing, we transmit the page over SSL and encrypt the View State Data. To encrypt the data, we have the ViewStateEncryptionMode Property, and it has the following 3 options.
- Always: Encrypt the data Always.
- Never: Encrypt the data Never.
- Auto: Encrypt any Control request, especially for Encryption
We can enable it by using.
- <%PageLanguage="C#"EnableViewState="trueViewStateEncryptionMode="Always"