Marcel
Marcel

Reputation: 15732

Why is viewstate serialized to a hidden field in the form and not kept on the server?

I am quite new to WebForms and I'm trying to understand the ViewState. AFAIK today, it keeps modifications of the UI over postbacks to the same page. But why does it send the state (= stored modifications) to the client and does not keep it on the server saving CPU cycles and bandwidth?

Am I understanding something completely wrong?

Upvotes: 4

Views: 913

Answers (2)

João Angelo
João Angelo

Reputation: 57718

The view state is something intrinsically connected to the view, as the name implies, and trying to manage it separately while maintaining that relation is not something that is easily accomplished.

You would need to store view state per page, so you would still have to send to the client an ID in order to be able to get the correct view state on a postback. Another serious issue is that you send a page to the client but you don't know when or if the client is going to postback that page to the server, so you would need to store view state at least until the session expires.

This could lead to a waste of server resources, as all those view states are being stored for users that may never postback to the server. If you keep your view state slim you'll agree that the best place to store it is to send it with view.

Finally, if you're still not happy with the view state on the client you can override the SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium methods of the page and save it to another medium. I've already heard many people complain about view state on the client, and most time I just tell them to go ahead and implement persistence to another medium on the server... however, I believe no one ever did, probably because it's complicated and you'll end up with a solution that's not that clean.

Upvotes: 3

user1429080
user1429080

Reputation: 9166

ViewState is used when a page performs a post back in order to restore the control tree of the page to what is was when the page was last rendered.

This allows for instance a GridView control to keep it's state (what is shown in the GridView) on post back without having to rebind it to the same data.

The reason why the ViewState per default is serialized and sent to the client is (I guess) that it's the easiest way to get it back when the client performs a post back.

What if for instance a user has several browser windows open with the same page loaded and you have the viewstate stored in the Session? Assigning the correct viewstate to the different windows in such a case can of course be solved, but having the client explicitly post it seems to be the easiest way.

That said, it is possible to have the viewstate stored in the Session. See for instance this link.

Other possibilities are available by implementing your own System.Web.UI.PageStatePersister.

Upvotes: 2

Related Questions