# 小新的技术天地

Make It Works !

## TRULY Understanding ViewState

ViewState is a very misunderstood animal. I would like to help put an end to the madness by attempting to explain exactly how the ViewState mechanism works, from beginning to end, and from many different use cases, such as declared controls vs. dynamic controls.

ViewState是一只非常容易让人误解的动物。我想结束为了尝试解释清楚ViewState的工作机制而搞得一团糟的状况，从头到尾，从各种不同的用例，比如说declared controls vs. dynamic controls（术语我都不翻了哈）

There are a lot of great articles out there that try to dispel the myths about ViewState. You might say this is like beating a dead horse (where ViewState is the horse, and the internet is the assailant). But this horse isn't dead, let me tell you. No, he's very much alive and he's stampeding through your living room. We need to beat him down once again. Don't worry, no horses were harmed during the authoring of this article.

It's not that there's no good information out there about ViewState, it's just all of them seem to be lacking something, and that is contributing to the community's overall confusion about ViewState. For example, one of the key features that is important to understand about ViewState is how it tracks dirtiness. Yet, here is a very good, in-depth article on ViewState that doesn't even mention it! Then there's this W3Schools article on ViewState that seems to indicate that posted form values are maintained via ViewState, but that's not true. (Don't believe me? Disable ViewState on that textbox in their example and run it again). And it's the #1 Google Search Result for "ASP.NET ViewState". Here is ASP.NET Documentation on MSDN that describes how Controls maintain state across postbacks. The documentation isn't wrong per say, but it makes a statement that isn't entirely correct:

"If a control uses ViewState for property data instead of a private field, that property automatically will be persisted across round trips to the client."

That seems to imply that anything you shove into the ViewState StateBag will be round-tripped in the client's browser. NOT TRUE! So it's really no wonder there is so much confusion on ViewState. There is no where I've found on the internet that has a 100% complete and accurate explanation of how it works! The best article I have ever found is this one by Scott Mitchell. That one should be required reading. However, it does not explain the relationship of controls and their child controls when it comes to initialization and ViewState Tracking, and it is this point alone that causes a bulk of the mishandlings of ViewState, at least in the experiences I've had.

So the point of this article will be to first give a complete understanding of how ViewState basically functions, from beginning to end, hopefully filling in the holes that many other articles have. After a complete explanation of the entire ViewState process, I will go into some examples of how developers typically misuse ViewState, usually without even realizing it, and how to fix it. I should also preface this with the fact that I wrote this article with ASP.NET 1.x in mind. However, there are very few differences in the ViewState mechanism in ASP.NET 2.0. For one, ControlState is a new type of ViewState in ASP.NET 2.0, but it treated exactly like ViewState, so we can safely ignore it for the purposes of this article.

First let me explain why I think understanding ViewState to it's core is so important:

MISUNDERSTANDING OF VIEWSTATE WILL LEAD TO...

1. Leaking sensitive data
2. ViewState Attacks - aka the Jedi Mind Trick -- *waves hand* that plasma tv is for sale for $1.00 3. Poor performance - even to the point of NO PERFORMANCE 4. Poor scalability - how many users can you handle if each is posting 50k of data every request? 5. Overall poor design 6. Headache, nausea, dizziness, and irreversible frilling of the eyebrows. 错误理解ViewState会造成 1. 丢失敏感数据 2. ViewSate攻击 - aka the Jedi Mind Trick -- *waves hand* that plasma tv is for sale for$1.00
3. 糟糕的性能甚至可以到达没有性能的程度
4. 糟糕的可伸缩性 如果每一次请求都post 50K的数据有多少用户可以处理
5. 糟糕的全局设计
6. 头痛，反胃，头昏眼花，皱眉头（这作者真是

If you develop an ASP.NET Application and you don't take ViewState seriously, this could happen to you:

The ViewState form data

ViewState will add your web app's distinctiveness to it's own. Performance is futile

I could go on but that is the gist of it. Now lets move on by starting back from the beginning:

WHAT DOES VIEWSTATE DO?
This is a list of ViewState's main jobs. Each of these jobs serves a very distinct purpose. Next we'll learn exactly how it fulfills those jobs.

1. Stores values per control by key name, like a Hashtable
2. Tracks changes to a ViewState value's initial state
3. Serializes and Deserializes saved data into a hidden form field on the client
4. Automatically restores ViewState data on postbacks

ViewState做了什么？

1. 通过键名，每一个控件保存一些值，就像Hashtable.
2. 跟踪对ViewState初始状态的改变。
3. 序列化和反序列化保存的数据到客户端一个隐藏字段里。（大家比较清楚的只有这点吧？）
4. postbacks时自动恢复ViewState数据。

While ViewState does have one overall purpose in the ASP.NET Framework, it's four main roles in the page lifecycle are quite distinct from each other. Logically, we can separate them and try to understand them individually. It is often the mishmash of information on ViewState that confuses people. Hopefully this breaks it down into more bite size nuggets. Mmmm... ViewState Nuggets.

To be continued…

Part2
http://www.cnblogs.com/wdxinren/archive/2006/09/30/519325.html

posted on 2006-09-30 09:53 小新0574 阅读(...) 评论(...) 编辑 收藏