原文:http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx
翻译:小新0574前几天看到思归同学推荐了几篇好文章,看了一篇确实觉得不错,。但是贴个链接,又是英文的,看的人就不会很多,我就翻译给大家吧。不过最近挺懒的,导致前一篇想翻译的文章 夭折,所以这次就分几次翻译好了.不过原文没有分成几部分,英文好的同学自己可以去看,不用等我哈。
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.已经有许多很好好的文章尝试驱散ViewState的神秘。你可能会认为这就像打一只死马(这里ViewState是那只马,internet是打的人)但让我来告诉你,这只马并不是死的。其实它十分活泼,在你的卧室惊跑(这作者还真能掰的…)我们需要再一次把它击倒。别担心,写这篇文章的时候没有马会受伤.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."其实并不是外界没有关于ViewState的好的资料,只是他们都缺少了一些东西,而造成整个社区对于ViewState的迷惑。比如说,其中一个关键特性就是,理解ViewState怎么tracks dirtiness是很重要的。然后,这里有一片很好的,深入的关于ViewState的文章似乎指出posted form values使用viewstate维护,但这是不正确的。(不相信我?Disable他们那个例子上的textbox的ViewState,再运行一次)。这是关于"ASP.NET ViewState"的#1 Google Search Result。这里是ASP.NET Documentation on MSDN,解释了Controls怎么across postbacks维护ViewState.这个文档每一句话都没错,当时他得出的一个statement并不完全正确:“如果一个控件为属性值使用ViewState来代替私有字段,这个属性会往返于客户端时自动被持久化”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.这好像暗示说,任何你扔给ViewState StateBag的东西,都会往返于客户浏览器。这不是真的!这么看来,对ViewState有这么对困惑真的一点都不奇怪了。我在internet真找不出能100%完全正确解释Viewstate是怎么工作的文章。我曾今找到最好的一片是this one by Scott Mitchell。这篇值得阅读。然而,这文章并没有解释控件和他们子控件在初始化和ViewState Tracking时的关系,而这正是造成大量误用ViewState的关键所在,至少在我的经验中是这样的。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.所以这篇文章的首先会给出一个关于ViewState基本功能的一个完整理解,从头到尾,希望能够堵上很多其他文章的漏洞。在对整个ViewState过程的完全解释以后,我会展示一些开发人员怎么误用ViewState的例子,通常他们根本不会意识到它,和也不知道如何修复它。我首先声明我这篇文章写得一些情况是对于ASP.NET 1.X而言的。然而,ASP.NET 2.0对于ViewState机制只有极少的更改。其中一点,ControlState在ASP.NET 2.0 中是一种ViewState的新类型,但是它跟ViewState几乎是一样的处理方式,所以我们可以很安全的忽略它。First let me explain why I think understanding ViewState to it's core is so important: 首先让我解释为什么理解ViewState的核心是很重要的:MISUNDERSTANDING OF VIEWSTATE WILL LEAD TO... Leaking sensitive data 
ViewState Attacks - aka the Jedi Mind Trick -- *waves hand* that plasma tv is for sale for $1.00 
Poor performance - even to the point of NO PERFORMANCE 
Poor scalability - how many users can you handle if each is posting 50k of data every request? 
Overall poor design 
Headache, nausea, dizziness, and irreversible frilling of the eyebrows. 
 错误理解ViewState会造成…丢失敏感数据 
ViewSate攻击 - aka the Jedi Mind Trick -- *waves hand* that plasma tv is for sale for $1.00 
糟糕的性能 – 甚至可以到达没有性能的程度 
糟糕的可伸缩性 –如果每一次请求都post 50K的数据有多少用户可以处理 
糟糕的全局设计 
头痛,反胃,头昏眼花,皱眉头(这作者真是…)
 If you develop an ASP.NET Application and you don't take ViewState seriously, this could happen to you:如果你开发ASP.NET程序而不严肃处理ViewState,这就会发生在你身上:
The ViewState form dataViewState will add your web app's distinctiveness to it's own. Performance is futileI 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. Stores values per control by key name, like a Hashtable 
Tracks changes to a ViewState value's initial state 
Serializes and Deserializes saved data into a hidden form field on the client 
Automatically restores ViewState data on postbacks 
 ViewState做了什么?这里是ViewState所作的主要工作的一个列表。每一个工作都达到了一个不同的目的。接下来我们会了解到它怎么完成这些工作的。通过键名,每一个控件保存一些值,就像Hashtable. 
跟踪对ViewState初始状态的改变。 
序列化和反序列化保存的数据到客户端一个隐藏字段里。(大家比较清楚的只有这点吧?) 
在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.由于ViewState全面参与了ASP.NET Framework,在页面生命周期中它的四个角色各不相同。逻辑上,我们可以分割他们,尝试单独一个一个理解他们。ViewState中混乱的信息经常使人们迷惑。希望它能被打碎成小到可以被咬的nuggets…ViewState Nuggets(这作者又来这招了…)To be continued… 
1.   VIEWSTATE STORES VALUES
If you've ever used a hashtable, then you've got it. There's no rocket science here. ViewState has an indexer on it that accepts a string as the key and any object as the value. For example: 如果你用过hashtable,那你已经知道这点了。这里没有关于火箭的科学。ViewState有一个indexer,接受一个string作为key,任何object作为value.比如说ViewState["Key1"] = 123.45M; // store a decimal valueViewState["Key2"] = "abc"; // store a stringViewState["Key3"] = DateTime.Now; // store a DateTime

解决方案 »

  1.   

    Actually, "ViewState" is just a name. ViewState is a protected property defined on the System.Web.UI.Control class, from which all server controls, user controls, and pages, derive from. The type of the property is System.Web.UI.StateBag. Strictly speaking, the StateBag class has nothing to do with ASP.NET. It happens to be defined in the System.Web assembly, but other than it's dependency on the State Formatter, also defined in System.Web.UI, there's no reason why the StateBag class couldn't live along side ArrayList in the System.Collections namespace. In practice, Server Controls utilize ViewState as the backing store for most, if not all their properties. This is true of almost all Microsoft's built in controls (ie, label, textbox, button). This is important! You must understand this about controls you are using. Read that sentance again. I mean it... here it is a 3rd time: SERVER CONTROLS UTILIZE VIEWSTATE AS THE BACKING STORE FOR MOST, IF NOT ALL THEIR PROPERTIES. Depending on your background, when you think of a traditional property, you might imagine something like this:  实际上,“ViewState”只是一个名字。ViewState是一个定义在System.Web.UI.Control类里的protected property,所有的服务器控件,用户控件,页面都继承自这个类。这个property的类型是System.Web.UI.StateBag。严格来说,StateBag跟ASP.NET一点关系都没有。除了它对也定义在System.Web.UI 的State Formatter的依赖之外,它只是碰巧被定义在System.Web assembly中,其实没什么理由让StateBag不能跟System.Collections中的ArrayList一起存在。实践证明,Server Controls utilize ViewState as the backing store for most, if not all their properties(因为这个在后面多次重复出现,而且作者特别强调,所以大家还是自己理解原文吧)。其实真的是几乎所有的Microsoft的东东都构建在控件里(ie, label, textbox, button)。这很重要!你必须理解你在使用的控件相关的东东。再读一遍这个句子。我的意思是…已经第三次了:SERVER CONTROLS UTILIZE VIEWSTATE AS THE BACKING STORE FOR MOST, IF NOT ALL THEIR PROPERTIES.根据你的背景。当你想起一个传统的property,你可能会想像这样一个东西:public string Text {
        get { return _text; }
        set { _text = value; }
    }
     What is important to know here is that this is NOT what most properties on ASP.NET controls look like. Instead, they use the ViewState StateBag, not a private instance variable, as their backing store: 重要的是要知道大多数ASP.NET控件的properties并不是这样的。而是,他们使用了ViewState StateBag, 而不是private instance variable作为他们的backing store:public string Text {    get { return (string)ViewState["Text"]; }    set { ViewState["Text"] = value; }}
    And I can't stress it enough -- this is true of almost ALL PROPERTIES, even STYLES (actually, Styles do it by implementing IStateManager, but essentially they do it the same way). When writing your own controls it would usually be a good idea to follow this pattern, but thought should first be put into what should and shouldn't be allowed to be dynamically changed on postbacks. But I digress -- that's a different subject. It is also important to understand how DEFAULT VALUES are implemented using this technique. When you think of a property that has a default value, in the traditional sense, you might imagine something like the following: 我实在受不了了 – 这是几乎ALL PROPERTIES,甚至是STYLES的真相(实际上,STYLES没有实现IStateManager接口,但是本质上他们的做法是一样的)。当你在写你自己的控件的时候,通常遵循这个pattern是个好主意,但是首先要考虑在postbacks时什么东东应该被允许动态改变,什么东东不应该被允许。但我有点离题了 – 这个另外一个主题。理解DEFAULT VALUES时怎么使用这个技术实现的也很重要。当你考虑到一个property有一个default value时,以传统的理解,你可能会想象下面这样的东西:public class MyClass {    private string _text = "Default Value!";     public string Text {        get { return _text; }        set { _text = value; }    }}
    The default value is the default because it is what is returned by the property if no one ever sets it. How can we accomplish this when ViewState is being used as the private backing? Like this: Default value之所以是default是因为如果没有人设置它,那么这就是它通过property返回的value.当ViewState被用来作为private backing时,我们又是怎么来完成的呢?就像这样:public string Text {    get {        return ViewState["Text"] == null ?             "Default Value!" :              (string)ViewState["Text"];    }    set { ViewState["Text"] = value; }}
      

  2.   

    个人任务viewstate还是少用的好
      

  3.   

    sorry,打错字了,我是想说
    个人认为viewstate还是少用的好
      

  4.   

    不好意思我么有权限修改
    大家还是到这个页面去看吧
    http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx