JavaEar 专注于收集分享传播有价值的技术资料 what to use instead of viewstate

Currently I am using the viewstate just to store the current page number I am on while paging through data. I have 3 controls on the page that have data I can page through.

So far the easiest way to keep track of the page number is the viewstate but it's getting really big and I have no idea why.

So I would like to use something else to keep track of the page number but I am not sure what to use. Should I embed it as a hidden form field? Pass it in the querystring? Other good options?


  1. You are stating you are using viewstate for storing the current page number, and by this I guess you are explicitly storing this number in viewstate.

    However, will by default store a lot of data in viewstate. In your example, having 3 controls with paging enabled, will store "all data in the control" i.e. all the data that is currently being shown in the 3 controls will be stored in viewstate.

    A solution to this could be to turn "off" viewstate on the 3 paged controls explicitly, unfortunately this means you will have to rebind the controls on each pageload, which may or may not be an option for you.

    If you just need to store the page-number, you could for instance move it into control-state as described on msdn and on pluralsight.

    Use a querystring as suggested in another answer.

    Or you could just continue to use viewstate, and then proceed to turn off viewstate for either the entire page or just the paged-controls, whatever works for you.

    I would really suggest reading Truly Understanding Viewstate by Mrunal Brahmbhatt for an in-depth explanation of viewstate.

  2. 参考答案2
  3. Storing the page number in the ViewState shouldn't take up that much room, so I think you should tackle the root of your problem.

    In ASP.Net the ViewState is turned on by default for each control. So a simple label with a static text will take up space in the ViewState. Turning this off will help a lot.

    Check out these two articles, they helped me a lot in the past:

    What version of ASP.Net are you working on? ASP.Net 2.0 has a lot smaller ViewState than 1.1.

  4. 参考答案3
  5. With stateless nature of HTTP it's hard to choose where to actually store your state. In your example I would consider the following instead of viewstate:

    1. Query string - page number is small enough to nicely fit there.
    2. Cookies - in this case your data will persist longer and will live through all the GET and POST requests.
    3. Session - almost similar to the previous option, but data will be stored on the server.
  6. 参考答案4
  7. Passing it in the query-string is a good option, this makes it "hackable" and good for SEO. So for page number, i'd never concider anything else than the url!