Search code examples
c#asp.netpostbackviewstate

Get raw ViewState data in code behind


I want to get raw ViewState data in code behind . Something like this :

private string GetRawViewState()
{
 // What code should be here.
}
// sample result : +9O4aKH/cgkvaOlTP4rWZotoC6yCtEXUhV2khD3IdEcQXc3wwdhiK2oOgWBVYsFmmZc60tR+Vu+XJRi9/9mpzrHbwDuvnq684rT+W8XywFHw2r3KdgVDVPqwHVL3TChORfmaBkcKAYlXf0Fl54PZ/FWfWB96s9fIf4/2iu57Wb0=

Solution

  • I see no simple way to do this.

    It's internal void Page.RenderViewStateFields(HtmlTextWriter) that renders the __VIEWSTATE field based on the serialized content in internal String Page.ClientState { get; set; }. The serialization is done by HiddenFieldPageStatePersister.Save(), but you can only access it via Page.PageStatePersister which is protected.

    So, there's no simple api call available for you to do this.

    A custom Page class (using <tagMapping> in web.config) would be able to access things with protected visibility, which means that you can access the PageStatePersister instance, but you do not have access to the serialized value. You could create your own ObjectStateFormatter and serialize the PageStatePersister.ViewState and PageStatePersister.ControlState property, but I am not sure that the values generated will be the same as those sent to the client.

    Reflection, on the other hand, can just read the Page.ClientState property. This is available to you in the Page.SaveStateComplete event, which occurs after PageStatePersister.Save() has been called internally. This is probably the easiest way to do this.