Does viewstate expire? - asp.net

Let's say you have a aspx page that does not rely on session, but does rely on viewstate for persistance between postbacks.
If a user is accessing this page, and leaves for a long lunch, will viewstate still be valid when he returns?

Viewstate itself does not expire. Since it's posted back in a form, it can be reconstituted any time.
According to MSDN: "...it is possible for view state to expire if a page is not posted back within the session expiration time". So, in a round about sort of way, it can expire if your session does, but viewstate does not directly expire. Since you're not using session state anyway, you don't have to worry about implicit expiration.
Note that I wouldn't have said it expired. That was MS who I quoted in their own article entitled Controlling ViewState

No ViewState is kept as part of the PostBack process. You can, however, override the Page class's SavePageStateToPersistenceMedium() and LoadPageStateFromPersistenceMedium(), to implement that behavior if desired. For more information read Understanding the ASP.NET ViewState.
Note that Page ViewState is stored in the Session so if your Session expires, the ViewState will be lost. I wouldn't say this is ViewState expiring, but yes, it will be destroyed after Session timeout.

Also, as a gotcha, by default ASP.NET encrypts ViewState with an autogenerated key. This can be overridden with the MachineKey element in the web.congif file. Even though ViewState won't expire, it can become invalid if a different autogenerated key is used to decrypt ViewState, such as after an IIS Reset, redeploying an application, or hitting a different server in a web farm. If you're planning on storing viewstate for long periods of time, watch out for how it's encrypted/decrypted.
http://msdn.microsoft.com/en-us/library/ms998288.aspx

Viewstate does not expire.
All viewstate data is stored on the client and is submitted back to the server when the user executes a postback.
This has some very interesting implications, and is explained very thoroughly here.

Yes, ViewState expires in certain conditions. For example when you are using iframe:s, or when you are upkeeping "live" connection to the server with regular postbacks. Then you might want to investigate this option: <sessionPageState historySize="9"/>, which actually hard-codes how many "postback results" are stored in the Session (if SessionPageStatePerster is used). Each postback stores it's ViewState to the end of the Queue in Session["__VIEWSTATEQUEUE"], and deletes ViewStates that are "too old". And how do you think SessionPageStatePerster decides which ViewStates are too old.. by configuring some arbitrary historySize-constant in web.config.. Omg! It too me forever to find this problem... My hatred toward asp.net programming is undescribable now.. grrr...

Viewstate does not expire, as long as they are still on the page, it will still be there and functional.

The ViewState will persist from POST to POST. It's actually stored inside a hidden field on your form so that it gets POSTed back to your server all the time.
As long as you aren't relying on the Session you shouldn't have any problems rebuilding page state. It's easy to test your Page's state code if you want though: just set your session to expire after 60 seconds in your web.config then load your page, wait a little more than a minute (surf over to Stack Overflow and answer some questions) and then click a button on your page.

Sorry to relive this old thread, but new information is available now:
Yes, ViewStates expire. I come from 19 hours researching about a problem of ViewStates losing its values between long time interval postbacks. It took me a while reading MSDN documents and Stackoverflow answers saying it was basically impossible to happen unless a custom ViewState storage implementation was employed, which, now I know, it's not true.
My problem was taking place in a SharePoint 2013 environment. The service known as Distributed Cache (a.k.a. AppFabric) does the caching of the ViewState and has a Time to Live associated to it. You can find more information here:
http://blogs.msdn.com/b/besidethepoint/archive/2013/03/27/appfabric-caching-and-sharepoint-1.aspx
The interesting bit of information can be found in this phrase:
"To improve page performance, beginning in SharePoint 2013 SharePoint caches ViewState data server-side rather than transferring it back and forth to clients."
I hope this information helps somebody so desperate as I was 19 hours ago.

ViewState is kept in a hidden field on the page itself. So as long as the user has the page, he'll have the ViewState. But if your app automatically logs the user out after a certain period of time, still having the ViewState may not do him any good.

By default, Viewstate is included with the html content as a hidden input. That means it won't expire, but that everything in viewstate must be uploaded from the user's browser. Since that's typically the slowest part of the connection in a public site, putting a lot of stuff in viewstate can quickly make your site seem very slow.

The short answer is: no.
The longer answer is: it depends on implementation of ViewState storage. You can provide custom implementation of ViewState which could expire after given amount of time. For example, you could store ViewState in database or on disk and send only some reference to the stored value in a hidden field. Then you can use batch processing to remove outdated ViewState data or perform expiration upon request.

No Viewstate doesnot expires.After redirecting to other page then value of view state lost or expire viewstate.
for more detail http://www.c-sharpcorner.com/UploadFile/78d182/Asp-Net-state-management-techniques/

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.

What is exact event(global.asax) to clear cache in asp.net

Im working on asp.net website.
In some pages I'm saving the datatable into chache as
cache["dt"]=dt;
and using whereever I want in that page by fetching from chache.
I'm thinking that whenever session close I want to clear session in session_end event of global.asax file.
as cache["dt"]=null;
What is the better location to close either application_end or session end.
If I close in session_end will it affect to another user?
Please provide me clear helpful info regarding this.
Thanks
Since you are putting the datatable in Cache, meaning, that it's shared by all the users, then there's no right place/need to do this, since the only time when it actually needs to be removed is when the application ends and at that point all resources are freed; your application is no longer running.
Perhaps what you should/meant to do was to put the datatable in Session. If that is what you want, then you could remove it OnSession_End in Global.asax but know that SessionEnd is not guaranteed to fire. You can also do Session.Abandon() when the user logs out, which will clear all session objects.
I think you misunderstood the concept between Application Data, Session Data, and Cache. These three of them all different things.
Application Data/State stores the information available in application scope, i.e. all session/user can access these data.
Session Data store info for the current session data. The duration of the session can be specified in the configuration files.
Cache stores frequently used data. And this data may be costly to regenerate every time.
In your case, since you are using cache, I assume that this cache stores some frequently used data. Ideally, this cache should always be valid, as long as the information does not changes.
As such, my recommendations is to keep this cache value as long as possible.

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.

asp.net server side viewstate without sessions

So I've done my best to minimize my viewstate on my ASP.net ajax application, http compression, disabling viewstate in hidden fields, but would like to go further. So after researching it seems that there are two approaches
a) use the ASP.net 1.x way which uses LoadPageStateFromPersistenceMedium
b) or use the ASP.net 2.x way SessionPageStatePersister
So B doesn't look good because if I understand it correctly the viewstate would be linked to the session id, and since my session can expire for any number of reasons I want don't want this.
So what's the best approach to saving viewstate on the server that does depend on sessions?
If it's LoadPageStateFromPersistenceMedium and uses hidden fields, then how do I inject a hidden field with a random id into a page?
How do I determine when it's time to clear viewstate files on the server?
I think you should seriously consider the Session option. It's optimal on resources and even if the Session expires if your Auth mechanism is alighed to session timeout it's not an issue.
http://professionalaspnet.com/archive/2006/12/09/Move-the-ViewState-to-Session-and-eliminate-page-bloat.aspx
As a fallback you could implement a Page base that puts the Session ID into the ViewState, checks it on postback and if it's different than does some action to recover.
The only other option you have would be to create your own PageAdapter that uses the DB or some other data store.
How about trying Flesk ViewState Optimizer?
Has several options including storing in session, in database, etc.

What is the difference between ViewState,Application and Session of a Page?

Please anyone explain me the difference between ViewState,Application and Session of a Page ?
Quick one liners - if you want more detail, just ask
ViewState is the variable that holds the current state of the page, which is held in a hidden field in the page (used frequently)
ApplicationState is a variable you can store values in during the life off the application (may get cycled periodically, and without your knowledge) (used less-frequently)
Session is the variable you can write to that will persist from the moment they hit your site until they close the browser. (barring any timeouts). (used frequently)
A great article :
How to Choose From Viewstate, Session, Application, Cache, and Cookies
Some good discussion about the difference between Session and Viewstate : Session Vs ViewState
Session state is saved on the server.
Session state is usually cleared after a period of inactivity from the user.
Can be persisted in memory, which makes it a fast solution. Which means state cannot be shared in the Web Farm/Web Garden.
Can be persisted in a Database, useful for Web Farms / Web Gardens.
Is Cleared when the session dies - usually after 20min of inactivity.
ViewState is saved in the page.
The view state is posted on subsequent post back in a hidden field.
Is sent back and forth between the server and client, taking up bandwidth.
Has no expiration date.
Is useful in a Web Farm / Web Garden
SESSION Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.
VIEWSTATE Variables are stored in the browser (not as cookies) but in a hidden field in the browser. Also Viewstate can hold only string data or serializable objects.
When we use view state to design a web application it retains it's state consistently, in it's current position. If we use session then it does not retain it's state, so when we refresh the browser it starts from the initial page.

Resources