In this post, we will explore how to remove ViewState from your asp.net page and instead store it in a session. This could be useful when pages are to be served to devices with less resources.
Since HTTP is a stateless protocol, the state of controls is not saved between postbacks. One of the ways to get around this is to use ViewState in ASP.NET. ViewState is the means of storing the state of server side controls in HTML hidden fields, between postbacks. For this example, on a button click, I have set the label text to ‘I Love DevCurry’. Here’s a sample viewstate shown below.
Although the viewstate looks decrypted, but it isn’t. It is a Base64 encoded string which can be decoded. You can easily use an online viewstate decoder to decode the string or read my post How to view information in ViewState using ASP.NET to create a simple decoder tool of your own.
Here’s the decoded viewstate
As you can see, the string that was stored in the viewstate can be seen once we have decoded the viewstate. You have a couple of options to protect your ViewState.
1. Encrypt ViewState - You can encrypt a ViewState by using the viewStateEncryptionMode option in your web.config or in your page.
2. The second option is to use the ViewStateUserKey Property to prevent web attacks.
3. The third option and the focus of this article is to remove the ViewState from the page and instead store it in a session state.
By default, view state is stored on the client using the HiddenFieldPageStatePersister class. However this option can be overridden and instead ViewState can be saved in a Session state using the PageStatePersister class. Add the following code in the code-behind of your page
That’s it. Run the page > Right click > view source > copy the viewstate and run it in the viewstate decoder. Here’s what you get.
As you can see, the viewstate no longer holds any values. That is because the viewstate is now stored in the session state.
Note: Use this approach carefully and selectively as you may run out of memory if you overuse it.
You may also want to read What's New in ASP.NET 4.0 – Better ViewState Control
Giving me +1 tells me you liked this article! Thanks in advance