Thursday, March 02, 2006

ASP.NET 1.1 - Save ViewState in Session

The team lead for a development group came to be today asking if there was anyway to reduce the size of the rendered page. This particular page requires significant legitimate use of ViewState. I knew I had read about saving ViewState to a custom store to override the default behavior of stuffing it into the page and sending it back to the client. This application is also using SQLServer to store session state.

So, the thought occurred to me that I should be able to store ViewState in Session. Below is the implementation in my Default.aspx

private string ViewStateName = "ViewStateName";

protected override object LoadPageStateFromPersistenceMedium()

{

string m_viewState;

LosFormatter m_formatter;

object viewStateBag;

m_viewState = Session[ViewStateName] == null ? null : (string )Session[ViewStateName];

m_formatter = new LosFormatter();

try

{

viewStateBag = m_formatter.Deserialize(m_viewState);

}

catch (Exception e)

{

throw new ApplicationException("The View State is invalid or corrupted", e);

}

return viewStateBag;

}

protected override void SavePageStateToPersistenceMedium(object viewStateBag)

{

// string file = GetFileName();

StringBuilder sb =

new StringBuilder();

StringWriter sw =

new StringWriter(sb);

LosFormatter formatter =

new LosFormatter();

formatter.Serialize(sw, viewStateBag);

sw.Close();

Session[ViewStateName] = sb.ToString();

}

No comments: