(32)Seven handy ViewState tips



Every time I have to deal with a classic ASP.NET Web Forms application, one of the first things I look at is the resulting source, to check whether the DOM is a complete mess and whether the ViewState is an enormous, unnecessary blob of ugliness. Usually, they indicate what kind of mess will be found further down the stack.
每次我不得不处理一个传统的ASP.NET Web Forms应用时,首先查看生成的源码,检查DOM是否一团糟、ViewState是否是很大,多余的丑陋代码块。通常,它们预示着发现的烂摊子会更烂。

<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wFzY3JpcHQ6IE9uY2xpY2s9J3dpbmRvdy5vcGVuKCJFcXVpcG1lbnQtRGV0YWlscy5hc3B4P1VzZWQtMjAxMC1UZXJl…(continues for 18,000 characters)…UlVTIiB3aWR0aD=” />
<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wFzY3JpcHQ6IE9uY2xpY2s9J3dpbmRvdy5vcGVuKCJFcXVpcG1lbnQtRGV0YWlscy5hc3B4P1VzZWQtMjAxMC1UZXJl…(此处省略18,000个字)…UlVTIiB3aWR0aD=” />

Inadvertently using ViewState when it’s not necessary substantially increases the amount of data going back and forth, and can lead to a greater prevalence of invalid ViewState exceptions; the bigger the blob, the more likely it could be interrupted in transmission and not be posted back in entirety in a post.

(33)Unless you’re tracking a Text_Changed event, you don’t need ViewState enabled on TextBoxes and similar controls. Classic ASP.NET automatically repopulates TextBox.Text values upon postback, even without ViewState enabled. Turn it off on each TextBox with EnableViewState= “false” on each one.



You can do this for other controls like labels, but unless you’re setting their values after the page’s load event, you won’t reduce the size of the ViewState.

(34)The same goes for most implementations of Repeaters, ListViews, and so on. These are usually the biggest culprits and they can be ugly. The advantage of ViewState with these is avoiding having to populate values again in a postback.


这同样适用于Repeaters, ListViews, 等等大多数的控件实现。这些通常可能成为丑陋的罪魁祸首。ViewState对于这些的优势是避免不得不在回发时重新填充值。

If you’re convinced that it’s worth passing ViewState back and forth again and again to save your app the extra database hit…well…you’re probably wrong. Save the database hit (if you need to) with some caching and disable that dang ViewState on that Repeater!

(35)If you’re re-binding data anyway, or just toggling one property on postback (asp:Panel anyone?), turn off that ViewState! Please!


如果你无论如何也要重新绑定数据,或者只是在回发时切换一个属性(asp:Panel 任何一个),请关掉ViewState!

(36)If you do need ViewState, understand the page lifecycle and bind your data appropriately. A control loads its ViewState after Page_Init and before Page_Load, i.e. server controls don’t start tracking changes to their ViewState until the end of the initialization stage.



Any changes to ViewState mean a bigger ViewState, because you have the before value and the after value. So, if you’re changing or setting a control’s value, set it before ViewState is being tracked, if possible.

(37)You may think it’s impossible to turn off ViewState on a DropDownList, even if you re-bind it on every postback. But with a tiny bit of elbow grease you can keep ViewState enabled and avoid passing all your option values back and forth. This is particularly worthwhile for DropDownLists with a big ListItem collection.



One way is to turn off ViewState and bind the select value manually to the actual posted value, like so:

string selectedId = Request[Countries.UniqueID];
if (selectedId != null)
Countries.SelectedValue = selectedId;

However, you may prefer something I came across more recently. Instead of binding your DropDown-List in the typical Page_Load or Page_Init, bind it in the control’s Init event:

<asp:DropDownList ID=”Countries” ...
OnInit=”CountryListInit” />
protected void CountryListInit(object sender, EventArgs e)
Countries.DataSource = // get data from database

(38)Make it your habit to turn off ViewState on every control by default, and only turn it on when you need it. If a page doesn’t need ViewState anywhere, turn it off at the page level.



You do all that work to reduce requests, combine and compress static references, and make sure your code is as clean as possible - don’t ruin it with a ViewState monster! If you’re anal, you can completely remove all traces of ViewState from pages that don’t need it by inheriting from a BasePage such as this:
你做所有工作来减少请求,合并和压缩静态引用,并确保你的代码尽可能的简洁 - 别让ViewState怪兽毁了它!If you’re anal(不知道怎么翻译),你可以继承一个基类页面,从页面完全移除所有的ViewState跟踪,像这样:

/// <summary>
/// BasePage providing cross-site functionality for pages that should not have ViewState enabled.
/// </summary>
public class BasePageNoViewState : Page // Or of course, inherit from your standard BasePage, which in turn inherits from Page
protected override void SavePageStateToPersistenceMedium(object viewState)
} protected override object LoadPageStateFromPersistenceMedium()
return null;
} protected override void OnPreInit(EventArgs e)
// Ensure that ViewState is turned off for every page inheriting this BasePage
base.EnableViewState = false;


  1. 教你50招提升ASP.NET性能(十六):把问题仍给硬件而不是开发人员

    (27)Throw hardware at the problem, not developers 招数27: 把问题仍给硬件而不是开发人员 As developers, we often want ...

  2. 教你50招提升ASP.NET性能(十九):静态集合

    (30)Static collections 招数30: 静态集合 If a collection is static, make sure it only contains the objects ...

  3. 教你50招提升ASP.NET性能(十八):在处理网站性能问题前,首先验证问题是否出在客户端

    (29)Before tackling any website performance issue, first verify the problem isn’t on the client 招数29 ...

  4. 教你50招提升ASP.NET性能(十五):解决性能问题时不要低估UI的价值

    (26)Don’t underestimate the value of the UI when tackling performance problems 招数26: 解决性能问题时不要低估UI的价 ...

  5. 教你50招提升ASP.NET性能(十四):使用startMode属性来减少ASP.NET站点加载时间

    (25)Use the startMode attribute to reduce the load time for your ASP.NET site 招数25: 使用startMode属性来减少 ...

  6. 教你50招提升ASP.NET性能(十):减少通过网络发送的数据

    (16)Reduce the data sent across the network 招数16: 减少通过网络发送的数据 Reducing the amount of data sent acros ...

  7. 教你50招提升ASP.NET性能(十二):在生产环境,仔细考虑你需要记录哪些日志

    (18)When in production, carefully consider what you need to log 招数18: 在生产环境,仔细考虑你需要记录哪些日志 Many peopl ...

  8. 教你50招提升ASP.NET性能(二十六):对于开发人员的数据库性能技巧

    Database Performance Tips for Developers对于开发人员的数据库性能技巧 As a developer you may or may not need to go ...

  9. 教你50招提升ASP.NET性能(十一):避免在调试模式下运行网站

    (17)Avoid running sites in debug mode 招数17: 避免在调试模式下运行网站 When it comes to ASP.NET, one of the most c ...


  1. 爬虫入门&mdash;&mdash;01

    1. 引言     从今天开始系统的学习网络爬虫.写这篇博客的目的在于,一来记录下自己的学习过程:二来希望可以给像我一样不懂爬虫但又对爬虫十分感兴趣的人带来一些帮助.     昨天去图书馆找有关爬虫书 ...

  2. SVN 常识

    1.相关博客 http://my.oschina.net/u/1780920/blog/425792 2. 文件红色:表示文件没有添加到服务器 绿色:表示没有更新新的修改到服务器 普通黑色:表示和服务 ...

  3. linux命令行netstat总结

    1.所谓的监听就是某个服务程序会一直常驻在内存中,所以该程序启动的Port就会一直存在. 2.在小于1023的端口,都是需要以root身份才能够启动的. 3.大于1024以上的Port主要是作为cli ...

  4. 点击某个按钮弹出 photoswip

    var openPhotoSwipe = function() { var pswpElement = document.querySelectorAll('.pswp')[0]; // build ...

  5. js 原生对象排序

    //对象属性排序 function compare(propertyName) { return function (object1, object2) { var value1 = object1[ ...

  6. MVC 过滤器

  7. 实现IEnumberable接口和IEnumberator

    class BookEnum : IEnumerator //实现foreach语句内部,并派生 { public Book[] _book; //实现数组 ;//设置“指针” public Book ...

  8. 监控持有sql和被堵塞的sql

    Session 1: mysql> start transaction; Query OK, 0 rows affected (0.00 sec) mysql> update Client ...

  9. 手把手在Ubuntu上面安装Docker

    一.环境准备 1.Ubuntu64位系统(目前docker仅支持64位系统) 2.官方支持的Ubuntu版本(1)Ubuntu Trusty 14.04(LTS)(2)Ubuntu Precise 1 ...

  10. nexus2 配置

    <?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Soft ...