Viewstate is not evil
- May 15th, 2011
- Posted in DotNet
- Write comment
Viewstate is often touted to be heavy and slow and better off disabled in most aspx applications. When used properly veiwstate can be quite a useful tool with not too much overhead. Use it improperly and all the horror stories you’ve heard start to come true …
If you view page source in an aspx application that has viewstate enabled site wide you will see the hidden __VIEWSTATE field will have a long encoded string of data. This is quite heavy and takes some time to trasmit betweeen the server and client. Our aim is to minimise the length of this data load to the point where overhead is no longer a concern.
First of all viewstate is enabled by default across the entire project so the first thing we need to do is turn it off. The idea is to opt in to viewstate rather than opt out. We only want to turn it on for the controls where we specifically want to maintain state.
In each masterpage or at the top of each page you can place this code in the page directive to disable the viewstate.
<%@ Page EnableViewState="False" ViewStateMode="Disabled"%> |
Or you can disable the viewstate across the whole application by putting this in the Pages tag in web config.
<Pages EnableViewState="false" /> |
Now that Viewstate is off by default … we can choose which controls we want to maintain state for. Most text fields and simple controls will be fine without viewstate. As a general rule leave it off until you have a specific reason to turn it on. The give away will be when you try to access the value of a control in code behind and get the default value no matter what value was set. In this case its time to turn on viewstate for that control only. We do this by using the same code as we did to turn it off …
<asp:DropDownList runat="server" ID="myDdl" EnableViewState="True" ViewStateMode="Enabled"/> |
You can add this to any control and access its value from a postback. If you view the page source again you will see the __VIEWSTATE field is much smaller … naturally the larger number of controls you enable viewstate for the larger the field will be.
Use it with caution but don’t write it off as bad practice.
No comments yet.