Partager via


Basic Sample - How To Keep ASP.NET ViewState On The Server

During recent few engagements with my customers I've noticed  VIewState is extensively [unintentionally] used. ViewState is on by default. The result is heavy weight Html that round trips on the network. This causes slow response time and high network utilization that affects another applications using the same network.

How to remove ViewState from the network completely while taking an advantage if its functionality at same time?

This post walks through basic steps of creating ASP.NET Base Page that implements functionality allowing saving ViewState on the server. The approach reduces dramatically network utilization.

Summary of steps

  • Step 1 - Create Visual Studio Solution.  
  • Step 2 - Implement Base Page
  • Step 3 - Inherit Each ASPX page from Custom Base Page
  • Step 4 - Test The Solution

The following section describes each step in details.

 

Step 1 - Create Visual Studio Solution.   Open Visual Studio 2008 and create empty solution, found under "Visual Studio Solutions". Name it BasePageSample. In Solution explorer right click the solution and add new project. Choose "ASP.NET Web Application" under Web node in "Add new Project" dialog. Name it SampleWebToUseExternalBasePage. Right click the solution in Solution Explorer and add new project. Choose "Class Library" under Windows node. Name it MyBasePage. In MyBasePage project add reference to System.Web assembly. Right click MyBasePage project and add new class, name it LeaveViewStateOnTheServer.cs.

 

Step 2 - Implement Base Page.   While in LeaveViewStateOnTheServer class add using declarations and inherit from Page type:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web;

 namespace MyBasePage
{
    class LeaveViewStateOnTheServer : Page
    {
    }
}

Override two relevant methods that handle Loading and Saving of ViewState:

 protected override object LoadPageStateFromPersistenceMedium()
{
    object viewStateBag;
    string m_viewState = (string)Session["ViewState"];
    LosFormatter m_formatter = new LosFormatter();
    try
    {
        viewStateBag = m_formatter.Deserialize(m_viewState);
    }
    catch
    {
        throw new HttpException("The View State is invalid.");
    }
    return viewStateBag;
}
protected override void SavePageStateToPersistenceMedium(object viewState)
{
    MemoryStream ms = new MemoryStream();
    LosFormatter m_formatter = new LosFormatter();
    m_formatter.Serialize(ms, viewState);
    ms.Position = 0;
    StreamReader sr = new StreamReader(ms);
    string viewStateString = sr.ReadToEnd();
    Session["ViewState"] = viewStateString;
    ms.Close();
    return;
}

This is a basic code that can be adopted and adapted to specific needs. The code mostly based on Dino Esposito's code.

Step 3 - Inherit Each ASPX page from Custom Base Page. Right click SampleWebToUseExternalBasePage project and reference to MyBasePage project. Right click SampleWebToUseExternalBasePage project and add new ASPX page, name it default.aspx. Open default.aspx.cs code behind and inherit the page from custom Base Page:

 using MyBasePage;

namespace SampleWebToUseExternalBasePage
{
    public partial class _Default : LeaveViewStateOnTheServer

Step 4 - Test The Solution. Add any control to the page from the toolbox. GridView uses ViewState the most. Here is how rendered Html For GridView looks with default ViewState behavior:

image

And here is how it looks without:

image 

 

My Related Posts

Related Resources

Download Sample Visual Studio 2008 solution from my SkyDrive:

Comments

  • Anonymous
    January 02, 2008
    What about if your customer uses more than one page in the same session? I think he won't be happy...
  • Anonymous
    January 02, 2008
    Dude, WAY Simplierprotected override PageStatePersister PageStatePersister       {           get           {               return new SessionPageStatePersister(Page);           }       }
  • Anonymous
    January 02, 2008
    saving viewstatesss to session? unless you are kidding me this is not for real world web applications.
  • Anonymous
    January 02, 2008
    @shuj - Good question! Dino has an aswer.from http://msdn.microsoft.com/msdnmag/issues/03/02/CuttingEdge/#S6"How should you choose the name of the file to ensure that no conflicts arise? The view state is specific to a page request made within a particular session. So the session ID and the request URL are unique pieces of information that can be used to associate the request with the right file. Alternatively, you could give the view state file a randomly generated name and persist the file name in a custom hidden field within the page"@Russ - I am not sure i get this.I need to do my H/W here. Thanks for the code.@kazlak - I think I know what you mean. I saw cases where session was not the option i saw also cases where it perfectly was. Both were very real to me :). Any way the sample demonstrate overrideing Page's ViewState relevant methods - way too many developers are not aware of it. The rest is up to your imagination - save it to Session, DB, files, even Cache [i did that too - we had our reasons for that - very real world reasons]. Yesterday i was at customer's where we implemented  it and explained implications of using session for saving ViewSate. He understood and accepted the risks. All is happy. What are the risks of using Session from your stand?
  • Anonymous
    January 02, 2008
    Sorry, should have included....http://msdn2.microsoft.com/en-us/library/system.web.ui.sessionpagestatepersister.sessionpagestatepersister.aspx
  • Anonymous
    January 02, 2008
    And, again because I can't put two thoughts into the same submission....The code that Dino goes into is great, we used a version of it for a while, but did run into problems when session would time out with out implimentation.What Dino's code also gives you is the ability to deploy this with all versions of .NET, where the SessionPageStatePersister is new to 2.0
  • Anonymous
    January 02, 2008
    alik am sure you understand the risks already, am more interested now to know scalable is the application you are referring to. things like how many concurrent users are you talking about? what is the server architecture that this application can be deployed to?.. etc
  • Anonymous
    January 02, 2008
    @Russ - be sure you got me hooked on this new feature and i am definitely going to do my H/W :) – thanks. BTW – w/r to session expiration, I hit the same problem once. This was the case where we decided to put into Cache – it is independent from Session and then we set proper expiration timeout.@kazlak – totally agree and I even – it is less scalable approach. I hate the fact I did not state it in first place – good catch! Imagine the situation where the application cannot breath…. Because of ViewSate of 400-600 Kb. It is in production and your end users are really mad at you. What would you prefer to make it breath or make the “right” architecture. Things like that. It depends where you at with the project – inception phase or fire alarm in production. That is why I am a big fun of PDL – performance development lifecycle. Doing right things during all dev stages. And not waiting for a fire alarm when in production
  • Anonymous
    January 08, 2008
    This is a follow up post to Basic Sample - How To Keep ASP.NET ViewState On The Server ASP.NET 2.0 offers
  • Anonymous
    January 15, 2008
    Ref:ArticleDuringrecentfewengagementswithmycustomersI'venoticed