-
ASP.NET 4.0: more control on viewstate management
-
ASP.NET is a stable and mature platform for building Web applications. Personally, I can hardly imagine a revolutionary set of new and compelling features to be added to it. So what's new in ASP.NET 4.0? Beyond AJAX stuff, there are some interesting enhancements in the Web Forms area. As I see things, all changes in ASP.NET 4.0 can be catalogued under the label of "more control". You get more control over viewstate, script references, ID generation, output caching and even, but in very limited form, over HTML generated by some controls.
Let's briefly focus on the viewstate extended control. In ASP.NET, the viewstate is optional but it is enabled by default. In addition, the viewstate is not simply a way of reducing your bandwidth. It is rather functional to the implementation of the Web Forms model. So just dropping the viewstate in a new version of ASP.NET is simply out of question: either you get a new ASP.NET platform such as ASP.NET MVC or you stick to Web Forms with the viewstate on board.
However, there's a subtle aspect of the viewstate management that has been fixed in ASP.NET 4.0. I said fixed because, well, from my perspective it had to be considered a bug-by-design in previous versions.
All server controls (the Page class derives from Control) have the EnableViewState property through which you can disable the viewstate for that control. What is little known ais that the EnableViewState property is ignored for child controls. In other words, if you take the default value (true) for the page, then whatever value you assign for it to any controls in the page... it is ignored. You can have have TextBox1.EnableViewState = false but still have the text box to read/write state from the viewstate if the viewstate is enabled at the page (or container) level.
This will change in ASP.NET 4.0 thanks to the new ViewStateMode property.
This property indicates whether the viewstate for the control is enabled|disabled|inherit. You can use the ViewStateMode property to enable view state for an individual control even if view state is disabled for the page. This is the great news. Finally, you can now disable the viewstate on the page and decide which controls will have it enabled (opt-in). In earlier versions you could only do the reverse (opt-out): enable the viewstate and then decide which controls will not support it.