How to Store view state at Server Side step by step

Dhirendra
Posted by in ASP.NET category on for Advance level | Points: 250 | Views : 13611 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article, we are going to learn how to store view state at server side in a file and retrieve the state for asp.net page processing.

Introduction

View state is a client side mechanism for storing the asp.net page's state in hidden form fields used by asp.net engine. By default, Asp.net engine stores this view state in hidden fields in base 64 format at client side browser window. In this article, I am going to explain how to store the view state at server side in a file system (or in the database)

Client side view state sample


 

ViewStateTest Page code

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

<!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>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="GetState" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductName], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [ProductID] FROM [Products]">
</asp:SqlDataSource>
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
<asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" SortExpression="ReorderLevel" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
</Columns>
</asp:GridView>
<br />
</form>
</body>
</html>

The above code show default behavior of the view state which renders the view state at client side.

In order implement server side storing the view state, we need override "LoadPageStateFromPersistenceMedium()" and "SavePageStateToPersistenceMedium(object state)" page events and write code to persist the view state in the file system or database. 

How SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium works?

Whenever first time page is request(get method) then SavePageStateToPersistenceMedium event calls to save the view state. When page is posted back to the server (IsPostback==true) then LoadPageStateFromPersistenceMedium events calls and then after the SavePageStateToPersistenceMedium event calls. So we can take advantage of this both events to persist the view state at server side in a persist media.

ViewStateTest Page code with Server Side view state


ASPX Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewStateTest.aspx.cs"Inherits="WebApplication70515.ViewStateTest" %><!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>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="GetState" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductName], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [ProductID] FROM [Products]">
</asp:SqlDataSource>
<br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
<asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" SortExpression="ReorderLevel" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
</Columns>
</asp:GridView>
<br />
</form>
</body>
</html>

C# Code (code behind)


using System;
using System.Web.UI;

using System.IO;

namespace WebApplication70515

{public partial class ViewStateTest : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected override void SavePageStateToPersistenceMedium(object state)

{

string file = GenerateFileName();

FileStream filestream = new FileStream(file, FileMode.Create);

LosFormatter formator = new LosFormatter();

formator.Serialize(filestream, state);

filestream.Flush();

filestream.Close();

filestream = null;

// base.SavePageStateToPersistenceMedium(state);

}

protected override object LoadPageStateFromPersistenceMedium()

{

object state = null;

StreamReader reader = new StreamReader(GenerateFileName());

LosFormatter formator = new LosFormatter();

state = formator.Deserialize(reader);

reader.Close();

return state;

//return base.LoadPageStateFromPersistenceMedium();

}

private string GenerateFileName()

{

string file=Session.SessionID.ToString() + ".txt";

file = Path.Combine(Server.MapPath("~/ViewStateFiles") + "/" + file);

return file;

}

}

}


The above code will write the view state in a file and will not render it at client side.

Screen shot (Output)


Conclusion


The above steps shows that how we can store the view state at server side in a file. Similarly we can store the viewstate into the database as well and can decrease the ViewState size load to the client that ultimately increases  the performance of the page.
Page copy protected against web site content infringement by Copyscape

About the Author

Dhirendra
Full Name: Dhirendra Patil
Member Level:
Member Status: Member
Member Since: 3/23/2010 2:39:20 PM
Country: India

http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)