Saving the Viewstate Server Side

5/28/2008

In ASP.Net, one of the great (and terrible) things that we have at our disposal is the viewstate. The viewstate ensures that we can hold onto the state of an item even between post backs without having to do anything. However if you've ever had to create a wizard to go through 10 or so states, had drop down boxes with 1000+ items, etc. you know that it can get extremely large, extremely fast. This of course translates to slower download speeds and unhappy people using your site (or more likely not using your site). So what can we do to help the situation?

Well in previous articles, I suggested various ways to compress the data that is being sent. However sometimes it doesn't matter how much compression you do, you're still going to have issues. So how do we fix this? Simple, don't send the information to the client. For instance the viewstate can instead be saved directly on the server in a file that we load at the appropriate time. If you look back at the ZippedPage code, you'll notice that we call LoadPageStateFromPersistenceMedium and SavePageStateFromPersistenceMedium. In them we end up using a hidden field called __ZippedState to store the information and send it to the end user. However we could instead use a streamwriter/streamreader and save the information to a file on the server instead. The only thing that we have to take care of is the file name, I mean how do we make sure that we don't write over the information when the next user queries a page?

Simple, Session ID...

   1: string URL = Request.ServerVariables["Path_Info"];
   2: URL = URL.Replace("/", "_"); 
   3:  
   4: string FileName = "{0}/{1}_{2}.vstate";
   5: FileName = String.Format(FileName, "Temp", Session.SessionID, URL); 
   6: FileName = Server.MapPath(FileName);

And that's all there is to it. FileName will now point to a file that is unique to the session and URL. From there you just serialize the viewstate to the file and voil??, you're done. Pretty simple and it has the ability to potentially save you tons on bandwidth. Anyway, try it out, leave feedback, and happy coding.



Comments