Environment:
Windows 2008, vs 2008 SP1, ASP. net mvc 1.0
------------------------------------------------------------------------------
I. tempdata in ASP. NET MVC
In the controllerbase of ASP. net mvc framework, there is a property called tempdata. Its type is tempdatadictionary. as its name implies, it is a dictionary class. The role of tempdata in ASP. net mvc is that it can be used to pass values between action execution processes. To put it simply, you can store data in tempdata when executing an action, so that the data in tempdata can be used during the next action execution.
For example:
The aboveCodeIn, index () adds a key-value pair to tempdata. Suppose we first request the index action and then the index2 action, then in index2, then we can obtain the key-value pairs added to tempdata. Interestingly, If you request index2 again, the value of myname read from tempdata will be null. Therefore, we need to understand the lifecycle of tempdata.
Ii. lifecycle of tempdata
We know that HTTP is stateless. Why can tempdata transmit data before two requests? Obviously, this data must have been saved in some form. ViewSource code, It is easy to find what we want:
The code above shows that the tempdata. Load () method must be called every time before the action is executed. After the action is executed, call the tempdata. Save () method. Another important member is tempdataprovider.
After reading the relevant source code, the truth is clear.
Tempdata. Load ()
Tempdata. Save ()
Tempdataprovider is used for temporary data storage. In the tempdata. Load () method, the data stored in the tempdataprovider is read to tempdata for use in the action call process. After the action is executed, tempdata. save () is to remove any key-value pairs not updated in tempdata and save the data in tempdata for the next call, only updated and newly added key-value pairs can be used in the next request ). Why does the data in tempdata need to be quickly cleared? It's easy, saving memory.
Iii. itempdataprovider
The tempdataprovider mentioned above is a property of the controller, which is defined as follows:
Here we see a default sessionstatetempdataprovider class. That is to say, ASP. net mvc stores tempdata through sessionstatetempdataprovider by default. Obviously, data exists in the session. That is to say, If you disable sessionstate, your page will report an exception.
ASP. net mvc is designed to be scalable. We can easily replace the default sessionstatetempdataprovider by implementing our itempdataprovider class. Note that the data stored by tempdataprovider must be user-independent.
The itempdataprovider interface is very simple to define:
In mvcfutures, you can also find a cookietempdataprovider that provides the implementation of storing tempdata in cookies.