X



Home>Tutorial>

What is ViewState, Advantages and Disadvantages of ViewState in ASP.NET

Nuelson Penuel Friday, August 28, 2020 ASP.Net

Summary

In this post, am going to teach you what is ViewState, advantages and disadvantages of ViewState, securing ViewState information as well as give examples.

Introduction

ASP.Net web application is developed to run on a standard protocol known as HTTP. In order words, a new instance of a page is created every time when a request is sent to the server to fetch a page. You may also like state management overview, see here; However, after this round trip to the server, the page state will be been lost immediately meaning all instances of created controls will be destroyed and values will be lost. So to overcome this problem, viewstate was introduced so controls state and values can be retained even after a complete round trip to server.

What is ViewState

ViewState is a client side state management technique that can be used for preserving user information within the same page after a round-trip to server.

Advantages of ViewState

1. It very easy to implement 2. It does not require server resources rather it leverage the server 3. View state data can be encoded and compressed

Disadvantages of ViewState

1. Information stored on view state can be seen clearly when the page source is viewed. 2. The page performance become slow if large data is stored on view state 3. View state requires high capacity of memory hence could degrade website performance on mobile phones. 4. View state can only store values for the same page only.

How to Enable and Disable ViewState

At default, asp.net enable view state, however, you can choose to enable or disable view state for single control or for the whole page. To turn off view for a whole page, set at the page directive as below
 <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" EnableViewState="false" Debug="true" Trace="true" %>
While to turn view state for a single control, use EnableViewState = "false" property of the control. Example is

<asp:Button ID ="Button1" runat="server" EnableViewState = "false"/>

Securing ViewState Information

Initially, view state data is stored in the form of Base 64 encoding but this encryption seems not to be secured because anyone with high or little skills of decryption can easily break it. However, asp.net provided two other options that can guarantee safety of your data stored in view state. These two options are ViewStateEncryptionMode and EnableViewStateMac. ViewStateEncryptionMode has three different options that can be set: Always: When this property is chosen, every data stored on ViewState will be encrypted always. Auto: Encrypt if a control requests for encryption. For this to happen, the control must call the Page.RegisterRequiresViewStateEncryption() method. Never: Never encrypt the ViewState.

Encrypting ViewState Data Using Message Access Control (MAC)

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 server. 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.

Preserving Data Using ViewState

In this example, the program will write to get the username and password inputted by the user and preserve it even after a postback. Here is the HTML source of the program
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.vb" Inherits="_Default" EnableViewState="true" Debug="true" Trace="true" %>
<!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>ViewState Example</title>
    </head>
    <body>
        <form id="form1" runat="server">
<asp:Label ID="lblstatus" runat="server" Text="" /><br/>
            <div>Username<br/>
                <asp:TextBox ID="txtusername" Text="" runat="server"/><br/>
Password<br/>
                <asp:TextBox ID="txtpassword" Text="" runat="server"/><br/>
 <asp:Button ID="btnsave" runat="server" Text="Save To ViewState" />
<asp:Button ID="btnread" runat="server" Text="Read ViewState" />
            </div>
        </form>
    </body>
</html>
Here is the code behind to write or save to ViewState. When this button is click, the person's username and password will be saved to ViewState. Here is the codebehind for saving to ViewState
Protected Sub btnsave_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If txtusername.Text = String.Empty And txtpassword.Text = String.Empty Then
       ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('Enter username and password');",True)
   Else
      ViewState ("uname") = txtusername.Text

ViewState ("pwd") = txtpassword.Text
End If
End Sub
Here is the code to read information from ViewState.
Protected Sub btnread_Click(ByVal sender As Object, ByVal e As EventArgs) 
    If Not ViewState ("uname") And ViewState("pwd") Then
       
 txtusername.Text = ViewState ("uname")
txtpassword.Text = ViewState ("pwd")

   Else
      
ScriptManager.RegisterStartupScript(Page,Page.GetType(),"mykey","alert ('No username and password found');",True)
End If
End Sub

| | Views(2781)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services