Sunday, February 16, 2014

ASP.NET ViewState example

ViewState is a client side state management mechanism. It is not the only state management mechanism. Some other examples would be,

For client side state management,
·         Hidden Field
·         Cookies
·         Control State

For server side,
·         Session
·         Application Object
·         Caching
·         Database

ViewState should be used to persist only small amounts of data as having lots of data in ViewState will degrade performance.

Also by default ViewState does not encrypt data but only encodes them to Base64. So generally sensitive data should not be kept there.

However you can encrypt ViewState by setting  ViewStateEncryptionMode="Always" as a page level directive,

<%@Page ViewStateEncryptionMode="Always" %>

 or for all pages by setting in web.config,

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

There is a lot of confusion about ViewState and Form input preservation on postbacks.
An example would be, how a textbox persists data even when View State is set to off.
This is because many ASP.Net controls (TextBox, ListBox, RadioButtonList etc) have implemented the IPostBackDataHandler interface and calls the LoadPostData(), which repopulates them.

Here is a small example of using ViewState persist state,
  1. Create a ASP.Net web application 
  2. Add a Web Form named ViewStateExample
  3. Paste the below given code to the apsx and apsx.cs files respectively
  4. Make sure to rename of the namespace LearnASPWebForms to your namespace


  
ViewStateExample.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewStateExample.aspx.cs" Inherits="LearnASPWebForms.ViewStateExample" %>



<!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 id="Head1" runat="server">

    <title>ViewStateExample</title>

</head>

<body>

    <form id="testform" runat="server">

        <asp:Label runat="server" Text="Enter a Value" />

        <asp:TextBox runat="server" id="FieldToBePreserved" /><br />

        <asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit and add to ViewState" />

        <asp:Button runat="server" id="SubmitDontSave" text="Submit but dont save to ViewState" OnClick="SubmitDontSave_Click"  />

        <br /><br />

        Value from ViewState: <asp:Label runat="server" id="ViewStateValue" BorderStyle="Dotted" />

    </form> 

</body>

</html>



CodeBehind ViewStateExample.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LearnASPWebForms
{
    public partial class ViewStateExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ViewState["Field"] != null)
                ViewStateValue.Text = ViewState["Field"].ToString();
            else
                ViewStateValue.Text = "Nothing in ViewState";
        }

        protected void SubmitForm_Click(object sender, EventArgs e)
        {
            ViewState["NameOfUser"] = FieldToBePreserved.Text;
            ViewStateValue.Text = FieldToBePreserved.Text;
        }

        protected void SubmitDontSave_Click(object sender, EventArgs e)
        {
            //This does nothing
        }

    }
}

0 comments:

Post a Comment