Maximizing.ASP.dot.NET.Real.World.ObjectOriented.Development [Electronic resources]

Jeffrey Putz

نسخه متنی -صفحه : 146/ 128
نمايش فراداده

Managing Viewstate

Viewstate can be a blessing and a curse in ASP.NET. You've already learned that viewstate helps ASP.NET simulate statefulness on a page. The problem is that too much viewstate can slow down your page for three reasons. First, a control's state must be saved into viewstate before the page is sent to the user. Then the actual sending of that viewstate uses precious bandwidth to get to the user. Finally, the viewstate has to be decoded when it is returned back to the server from the user. This process can take up precious CPU time, and it can fill your pipe with redundant data. If you don't need it, don't use it!

Fortunately, disabling viewstate is easy to do, by page or individual control. The Page directive (and Control directive, if you're using a user control) has an enableViewState attribute that you can set to false. This means that no controls on the page will use viewstate, and the hidden field in the HTML will result in just a handful of bytes. It's important to know that this high-level declaration affects everything below it, so you can't turn on viewstate for any controls on the page.

Every control has an EnableViewState property because all controls inherit from System.Web.UI.Control (including the Page object). You can set this property declaratively or programmatically. The general rule I use is that if the control can't be altered by the user (like a Label control), and I can set the control's value on the server side, it's safe to turn off viewstate.