Server Side View State In ASP.NET

Introduction

View State is a State Management technique by which we store the data during the page post-back. Basically View State is a client-side State Management technique. We know that the web applications are stateless because they use the HTTP protocol and HTTP is a stateless protocol. The data saved in a View State will be stored in a hidden format. The main purpose of a View State is to maintain the state of the controls during the page post-back event. When we send or receive a request for the server then every time a new instance of the page is created. So using the View State we store the page value during the page post-back. View State is a 64 bit serialized string code in hidden format on the page and when the user makes a request then this data moves from the server to the client and the client to the server depending on the user request. Please note one thing here, that the page does not have the automatic cleared property when the end user clicks on the submit button. One thing here is clear that the value of the View State does not work for the multiple pages.

Now first I tell you about the client-side View State technique and then we will explain the server-side View State Management technique.

Client-side View State

Step 1

Open the Visual Studio, go to the new project, add a ASP.NET empty web application.



Step 2

Then right-click on the Solution Explorer, add a new item and then add a new web form.



Step 3

Now in theWebForm1.aspx we write the following code.

Code

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.     <table>  
  13.         <tr>  
  14.             <td>  
  15.                 Name::  
  16.             </td>  
  17.             <td>  
  18.                 <asp:TextBox ID="txtname" runat="server"></asp:TextBox>  
  19.             </td>  
  20.             </tr>  
  21.         <tr>  
  22.             <td>  
  23.                 father Name::  
  24.             </td>  
  25.             <td>  
  26.                 <asp:TextBox ID="txtfathername" runat="server"></asp:TextBox>  
  27.             </td>  
  28.             </tr>  
  29.          <tr>  
  30.             <td>  
  31.                 City::  
  32.             </td>  
  33.             <td>  
  34.                 <asp:DropDownList ID="DropDownList1" runat="server">  
  35.                     <asp:ListItem>--select--</asp:ListItem>  
  36.                     <asp:ListItem>Delhi</asp:ListItem>  
  37.                     <asp:ListItem>Noida</asp:ListItem>  
  38.                     <asp:ListItem>Bareilly</asp:ListItem>  
  39.                     <asp:ListItem>Gaziabaad</asp:ListItem>  
  40.                     <asp:ListItem></asp:ListItem>  
  41.                 </asp:DropDownList>  
  42.             </td>  
  43.             </tr>  
  44.         <tr>  
  45.             <td>  
  46.                 Gender::  
  47.             </td>  
  48.             <td>  
  49.                 <asp:RadioButtonList ID="RadioButtonList1" runat="server" RepeatDirection="Horizontal">  
  50.                     <asp:ListItem>Male</asp:ListItem>  
  51.                     <asp:ListItem>Female</asp:ListItem>  
  52.                 </asp:RadioButtonList>  
  53.             </td>  
  54.             </tr>  
  55.         <tr>  
  56.             <td>  
  57.                 <asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="btnsubmit_Click" />  
  58.             </td>  
  59.             <td>  
  60.                 <asp:Button ID="btnrestore" runat="server" Text="Restore" OnClick="btnrestore_Click" />  
  61.             </td>  
  62.             </tr>  
  63.   
  64.     </table>  
  65.     </div>  
  66.     </form>  
  67. </body>  
  68. </html>  
Step 4

Then open your WebForm1.aspx .cs and write the following code.

Code
  1. using System;  
  2.   
  3. namespace WebApplication1  
  4. {  
  5.     public partial class WebForm1 : System.Web.UI.Page  
  6.     {  
  7.         public string Name, fatherName, City, Gender;  
  8.         protected void Page_Load(object sender, EventArgs e)  
  9.         {  
  10.   
  11.         }  
  12.   
  13.         protected void btnsubmit_Click(object sender, EventArgs e)  
  14.         {  
  15.             ViewState["Name"] = txtname.Text;  
  16.             ViewState ["fatherName"] = txtfathername.Text;  
  17.             ViewState["City"] = DropDownList1.SelectedItem.Text;  
  18.             ViewState["Gender"] = RadioButtonList1.SelectedItem.Text;  
  19.             clear();  
  20.               
  21.         }  
  22.   
  23.         protected void btnrestore_Click(object sender, EventArgs e)  
  24.         {  
  25.             if (ViewState["Name"] != null)  
  26.             {  
  27.                 txtname.Text = ViewState["Name"].ToString();  
  28.             }  
  29.             if (ViewState["fatherName"] != null)  
  30.             {  
  31.                 txtfathername.Text = ViewState["fatherName"].ToString();  
  32.             }  
  33.             if (ViewState["City"] != null)  
  34.             {  
  35.                DropDownList1.SelectedItem.Text = ViewState["City"].ToString();  
  36.             }  
  37.             if (ViewState["Gender"] != null)  
  38.             {  
  39.                RadioButtonList1.SelectedItem.Text = ViewState["Gender"].ToString();  
  40.             }  
  41.         }  
  42.         public void clear()  
  43.         {  
  44.             txtname.Text = "";  
  45.             txtfathername.Text = "";  
  46.             DropDownList1.SelectedItem.Text = "";  
  47.             RadioButtonList1.SelectedItem.Text = "";  
  48.   
  49.         }  
  50.     }  
  51. }  
This is a simple client-side View State example. First when we click on the submit button the data goes and is stored in the View State and when we click on the restore button the data comes from the View State and is shown on the page. When we run the application we get the following output:



Step 5

Now at that page in the browser where your application is running right-click on it and click on the view page source. There you will find your View State in encrypted format.

Code
  1. <div class="aspNetHidden"><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="8LrMyuvVAZko9eSik2wPrQK4zScyasSQS0fbKWCDypaCaLeSfUQsYSc1d50IbUNqcUx1J7DNEW7dGalHzTBjFrGeHVxmwiDzXVgeoAGGWTM8I6JVj0d9+iRcW9HJg3McSfqPq1yNSIokt2ShPZh8lMmt+mKPIg2MPfAtnixAiaU5bQQkOxp2Pp9ztgljl5lD+Wnz4BqzA6PRylHXMfvGjvegUcGOLVPPxUTvcCxoXH+XL/Zhkco1BdRaIPXM1Ssh" /></div>  
So this is a client-side View State where we preserve the data during the page post-back method and call that data again and again on a similar page.

Now here we will discuss the Server-side View State.

Server-side View State 

As I said above that View State stores the information during the page post-back. It stores the value of the server controls in a web form. The main advantage of View State is that it retains the control's values. The main problem with client-side View States is that when we convert our ASP web site into an ASP.Net web site we get an exception related to the View State and that exception is "The View State is invalid for this page and might be corrupted". So what are the reasons for this exception? The reason is that when the server redirecting is done the end-user sometimes uses the corrupt version of that page at which his/her View State exists because if there is any change in the hidden View State value then there will be an exception generated.

The other reason is that many browsers do not support the large hidden field inside it and sometimes when we make a View State there may be a large hidden file generated for the View State. So this is another reason to overcome this problem to save the View State at the server using the session object.

So now I have explained how to make a Server-side View State.

Step 1

For making a server-side View State we first must override "LoadPageStateFromPersistenceMedium()" and then override the "SavePageStateToPersistenceMedium" that are the page events. Then we write the View State code in the database or the file system depending on our needs.

The working of the LoadPageStateFromPersistenceMedium() and the SavePageStateToPersistenceMedium is totally dependent on the View State size. When the end user makes a request for the first time to use the page then by default SavePageStateToPersistenceMedium emerges. The main work of this event to save the View State, but when the user did not send the request the first time, in other words when the post-back event is true then the first LoadPageStateFromPersistenceMedium is generated and then the SavePageStateToPersistenceMedium occurs.

Step 2

Now again open the Visual Studio, go to the new website and add it.

Step 3

Go to the Solution Explorer, right-click on it and add a new Web form. And we also make a database table by which we bind the data in our grid view. That grid view is used by us in the following code.

The WebForm2.aspx code

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.    <div>  
  12. </div>  
  13. <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
  14. <br />  
  15. <br />  
  16. <br />  
  17.         <asp:Button ID="Button1" runat="server" Text="GetState" />  
  18.         <br />  
  19.         <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">  
  20.             <Columns>  
  21.                 <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />  
  22.                 <asp:BoundField DataField="FatherName" HeaderText="FatherName" SortExpression="FatherName" />  
  23.                 <asp:BoundField DataField="rollno" HeaderText="rollno" SortExpression="rollno" />  
  24.                 <asp:BoundField DataField="designation" HeaderText="designation" SortExpression="designation" />  
  25.             </Columns>  
  26.         </asp:GridView>  
  27.         <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:rizzuConnectionString %>" SelectCommand="SELECT * FROM [rizwan]"></asp:SqlDataSource>  
  28.     </form>  
  29. </body>  
  30. </html>  
Step 4

Then we write the code in the following.

WebForm2.aspx.cs file Code
  1. using System;  
  2. using System.Web.UI;  
  3. using System.IO;  
  4.   
  5. namespace WebApplication1  
  6. {  
  7.     public partial class WebForm2 : System.Web.UI.Page  
  8.     {  
  9.         protected void Page_Load(object sender, EventArgs e)  
  10.         {  
  11.   
  12.         }  
  13.   
  14.         protected override void SavePageStateToPersistenceMedium(object state)  
  15.         {  
  16.   
  17.             string file = GenerateFileName();  
  18.   
  19.             FileStream filestream = new FileStream(file, FileMode.Create);  
  20.   
  21.             LosFormatter formator = new LosFormatter();  
  22.   
  23.             formator.Serialize(filestream, state);  
  24.   
  25.             filestream.Flush();  
  26.   
  27.             filestream.Close();  
  28.   
  29.             filestream = null;  
  30.   
  31.         }  
  32.   
  33.         protected override object LoadPageStateFromPersistenceMedium()  
  34.         {  
  35.   
  36.             object state = null;  
  37.   
  38.             StreamReader reader = new StreamReader(GenerateFileName());  
  39.   
  40.             LosFormatter formator = new LosFormatter();  
  41.   
  42.             state = formator.Deserialize(reader);  
  43.   
  44.             reader.Close();  
  45.   
  46.             return state;  
  47.   
  48.         }  
  49.   
  50.         private string GenerateFileName()  
  51.         {  
  52.   
  53.             string file = Session.SessionID.ToString() + ".txt";  
  54.   
  55.             file = Path.Combine(Server.MapPath("~/ViewStateFiles") + "/" + file);  
  56.   
  57.             return file;  
  58.   
  59.         }  
  60.   
  61.     }  
  62. }  
Now when we run the application we will see it in the browser like this.



And now here our View State is stored in the ViewStateFiles folder that are present in our application. Here our View State code is like the following:
  1. /wEPGAEFCUdyaWRWaWV3MQ88KwAMAQgCAWQPBQoxNDE4NjIwMDUzD2QWAgIDD2QWAgIFDzwrABEDAA8WBB4LXyFEYXRhQm91bmRnHgtfIUl0ZW1Db3VudAIDZAEQFgAWABYADBQrAAAWAmYPZBYKAgEPZBYIZg8PFgIeBFRleHQFBlJpendhbmRkAgEPDxYCHwIFBXNhaGlsZGQCAg8PFgIfAgUHVENBMTEwMmRkAgMPDxYCHwIFB01hbmFnZXJkZAICD2QWCGYPDxYCHwIFBFNhYWRkZAIBDw8WAh8CBQVzYW1hcmRkAgIPDxYCHwIFB1RDQTExMDhkZAIDDw8WAh8CBQZIZWxwZXJkZAIDD2QWCGYPDxYCHwIFBFJhdmlkZAIBDw8WAh8CBQZyYW1lc2hkZAICDw8WAh8CBQhUQ0ExMTA4OWRkAgMPDxYCHwIFC2NvYXJkaW5hdG9yZGQCBA8PFgIeB1Zpc2libGVoZGQCBQ8PFgIfA2hkZA==  
Now when you right-click on the running page there is no hidden field for View State. Then another method makes a server-side View State. To see it Click here to know.

Advantages of server-side View State

The main advantage is that if a browser does not support a large encrypted file that is generated by the client-side View State then by the client-side View State we can handle it. As we know sometimes when we open an ASP web site in ASP.NET there will be some time corruption problem so it also minimizes the corruption problem. It also converts large client-side pages into a small client-side page because the View State data is stored at the server.

Disadvantages of Server-side View State

The main draw back is that the developer does not know how much space is taken by a View State on the server. If it takes a very large space there will be a problem. Another disadvantage is that server-side View State uses the server memory for the session object.

Summary

Everyone accepts that View State is a very important State Management technique for storing the data during the post-back. Here I explained how to store your View State on the client-side as well as server-side. Since sometimes the user faces the problem with the client-side View State there is another option to store it server-side. So by server-side View States we overcome all the problems that I said above. I hope this article will be useful for the reader.


Similar Articles