Thursday, November 24, 2011

How to Store Viewstate to Persistence Medium



In this article we will discuss about How to store ViewState of a Page/Control on server or a custom data store like sql server or file.
As you all know ViewState is stored as part of html sent to your browser in form of hidden field. This is the default behavior of asp.net framework. Starting asp.net 2.0 you have more control over how & where view state should be stored? First of all let’s understand the reason behind not sending viewstate to client:-
1.)    ViewState can be tempered with on client side with tools like firebug, fiddler etc.
2.)    ViewState makes page bulky and page loading process becomes slow.

Asp.net 2.0 introduced two methods which help us out in this process:-
1.)    LoadPageStateFromPersistenceMedium
2.)    SavePageStateToPersistenceMedium
LoadPageStateFromPersistenceMedium loads viewstate data from your custom storage.
SavePageStateToPersistenceMedium saves viewstate data to persistence medium.
So let’s try to understand this with an example
1.   Create an empty website in visual studio
2.   Add a page say Default.aspx
3.   Write below code in aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>
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">
<div>
<table>
<tr>
<td>
<asp:DropDownList ID="DropDownList1" runat="server">
asp:DropDownList>
td>
tr>
<tr>
<td>
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
td>
tr>
<tr>
<td>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
td>
tr>
table>
div>
form>
body>
html>

4. In code behind file write below code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem("1"));
items.Add(new ListItem("2"));
items.Add(new ListItem("3"));
DropDownList1.DataSource = items;
DropDownList1.DataBind();
}
}
protected override object LoadPageStateFromPersistenceMedium()
{
if (Session["DefaultPageViewState"] != null)
{
       string viewStateString = Session["DefaultPageViewState"] as string;
TextReader reader = new StringReader(viewStateString);
LosFormatter formatter = new LosFormatter();
object state = formatter.Deserialize(reader);
return state;
}
else
return base.LoadPageStateFromPersistenceMedium();
//return null;
}
protected override void SavePageStateToPersistenceMedium(object state)
{
LosFormatter formatter = new LosFormatter();
StringWriter writer = new StringWriter();
formatter.Serialize(writer, state);
Session["DefaultPageViewState"] = writer.ToString();
}
}
Open page in browser and page loads up with values in dropdown list.



Right click page and click View Source. See highlighted portion below..The viewstate field is empty.

Click the button to perform postback. You will see the dropdown still loads with data i.e. ViewState has been persisted and is working fine.
Just to cross check if our code is actually working. Comment out code in LoadPageStateFromPersistenceMedium method and return null instead. Again compile and run the code. Page will open fine first time but now click on postback , you will see dropdown losing data since it was stored in viewstate.