Where is ViewState stored? - asp.net

Where is a ViewState Stored? Is it stored in Server or Client Side?
I have a huge data which should be stored for some process. I was using Session. But when moved from one page to another im not able to clear the session. So I thought of implementing ViewState. But when running with huge amount of data ViewState is throwing error?
How can I resolve this?

Viewstate is stored on page it self in encoded form. You can't access the viewstate in client side in a direct manner. You need to know the encoding/decoding algorithms to fetch the valuable data from this viewstate in clientside code.
You can use hidden variable to store data that will be used only on that page. Hidden variables are accessible from client side and server side code.
You can use Cache or session to store datatable (large data). They will have good performance as compare to ViewState.
The Cache is always using the machine's memory, the Session uses what has been configured:
In a web farm the Session can be local (which works only if affinity is set), or remote (state server or database, or custom), but the cache is always local.
So, storing a DataTable in the cache will consume memory, but it will not use serialization.
PS: storing a DataSet instead of a DataTable will change almost nothing.
Refer Cache Implementation

The ViewState is not stored on either side, it's send back and forth between the server and the browser on every request and response, so it's not a good idea to put a huge amount of data in ViewState.

ViewState is stored where you tell it. By default, this is in a hidden field on the page sent to the client.
ASP.NET can also store ViewState inside the Session, i.e. on the server, if you tell it to.

Save large amount of data in view-state slowdown your site.
Use query string to fetch fresh copy from database on each page rather than save whole information from previous page.

View State Information stores in hidden fields.
Information travels between server and client in this hidden fields.
For asp.net control,.. by default .net implements view state for all its control, thats why a textbox value does not lost when we click on a button of that page.

Related

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?
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.
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.

Does ViewState require Server resources? I thought not

I read this somewhere:
"Because the view state for a given page
must be kept ON THE SERVER, it is possible for the current
state to be out of synchronization with the current page of
the browser, if the user uses the Back feature on the
browser to go back in the history"
I suspect that this may not be the default setting but instead an option to store the viewstate on the server, as what would the point of storing the ViewState in the page AND the server be? Am I correct?
If ViewState is stored on the server, how does one avoid the BackButton isue described here?
ASP.NET ViewState is stored in the client in one (or more) hidden HTML input field. I'd be really interested in seeing where you read that incorrect statement.
The server totally forgets ViewState once sent. As a security measure against tampering, ASP.NET can encrypt it and validate it against its key. If you use a set key (rather than auto-generating one), that view state will be valid even if the server has been shut down and rebooted entirely. All which illustrates that nothing in view state is stored on the server.

Alternative to ViewState

I'd like to store a few variables which will be referenced throughout lifecycle, starting with a db access in PreInit event. ViewState isn't an option, since it won't persist if saved so early during the page lifecycle. Given that data should not be altered by a user, what would be the best alternative?
You could use the Session to store your data. I am not sure on the number of users of your system, but assuming the data you want to store is small this won't be a problem.'
Also, unless you are using a SessionPageStatePersister (or another server side persister) or encrypting your ViewState it is still possible for the user to change the ViewState. It may be harder, but it is still possible. By default ViewState uses HiddenFieldPageStatePersister and it stores the ViewState in a hidden field on each page (as an encoded string). Just something worth considering.
Depending on the scope: Session or Application
Session
If you want the data stored per user
Application
If you want the data stored available for all users
You could store data in hidden fields, and if you want to obscure it, you could use some kind of encription. Of course these values would also only load in a later stage of the page lifecycle. The session object would be the obvious choice, although it's not everybody's favourite method.
Session probably wouldn't be available at PreInit, but you could store them in variables until a later page lifecycle task, and then store them in session at that time. I could be wrong about the session feature. Additionally, cache is an option but caching is not user-specific; you can make it user specific by appending their user ID or session ID.
Session is probably your best bet. We have to use the session to store some user information, but hit a bug due to accessing it too early. The bug is [HttpException]: Session state has created a session id, but cannot save it because the response was already flushed by the application." But it will often manifest as PageRequestMangerParserErrorException. Super fun hunting that down. One hackish fix is to write into your Global.asax code behind:
public Session_Start(object sender, EventArgs e)
{
string sessionId = Session.SessionID;
}
Accessing the SessionID forces the ASP.NET engine to go build the session before it normally would, making it possible to use it early.
Outside of session (or application) you have two other options: client storage and persistent storage. The latter is a fancy way of saying "stuff it in the database", though similar alternatives exist, of course.
Client Storage is like viewstate, but more controlled. You can use hidden fields or cookies. In fact, a cookie might work out well for you, but you'll need to encrypt the information in it if you want the user to leave it alone. Regardless, anything you send to the client you must assume is compromised, so always do a validity check.

How can i keep a data table thorough out my page?

Hii,
I have a data table, and this datatable will be dynamically manipulated. After certain manipulation at the end we will populate that to the database. Which state mechanism can i use for this to retain. I have tried both Session and ViewState but ViewState can't use with AJAX rich appplications. Session will be clear after the user session. i can't afford both these difficulties. Does any other mechanism to keep the datatable through out the page.
You can use Application variables if you need to persist state between users or sessions.
Have you considered storing your Session state in SQL Server? This would avoid the timeout of the session in IIS.
Have you considered using the ASP.NET runtime cache?
Cache["Foo"] = bar;
This cache is kept in memory and "lives" as long as the host application does.

How to cache a List of objects in ASP.NET

I have a List of objects in an asp.net page. when the page loads in the browser for the first time, I fetch data from the database, create objects with those data and populate the list. All these are done inside the page load event handler. Now when the page is posted back to the page, the previous list is gone, since the variables were all freed.
How can I cache that List, so that when this page is posted back, all my objects are available?
As #Eilon asked, is this data user-specific or is it site specific?
If the data is user specific you can use the Session State to store it, however it will expire when the users session ends, and in some cases can still invoke a roundtrip to your database server (if for instance it is backed by SQL server instead of being in-proc, etc).
If the data is application wide you can also use the Application Cache. It is site wide, resides in the process domain and is therefore available to everyone who has sessions on that server. Special care must be taken when using this in a multi-server scenario, but it is easily doable.
It should be noted that the Application Cache (and any other global setup) can make your app load slow for the first user to hit the site if the setup takes time. IIS7 and ASP.NET have attempted to address this with a module released recently that periodically wakes your app up to ensure that the global cache is either pre-populated, or remains alive.
Use Cache.Add(key_name, list_object, ...) to save the list, and then Cache[key_name] to retrieve it (you will need to cast the retrieved object to the appropriate type). The Add method has several more parameters to specify if and when the cached object expires.
The Cache object is actually System.Web.Caching.Cache and is accessible from your aspx page, or as HttpContext.Current.Cache.
if it's only relevant for this page, i would use the ViewState.
The syntax is familiar if you used sessionstate before:
to set:
ViewState["Persons"] = new List<Person>();
to read
List<Person> persons = ViewState["Persons"] as List<Person>;
The viewstate data is only kept for this page, but is sent as (serialized) text with your page, so don't use it for 1000 Persons because your page will be a very large download .
If you have lots of data, you're better of using the Cache object, but only if you're not on a web farm and remember to clear the data once in a while when you no longer need the data and use a cache key per user if it is per user data.
Last you can use the Session state, it is a per-user store, but remember to clear the data once in a while when you no longer need the data.
So, a lot to choose from depending on the situation.
Michel
use HttpContext.Current.Session.
To add to GrayWizard's answer, you can use viewstate too, but since it's included in postbacks, make sure you're not persisting something that takes up alot of space or needs to be secure since it's not encrypted by default.
Here's an overview - it's dated, but still relevant.
http://msdn.microsoft.com/en-us/magazine/cc300437.aspx

Resources