The following sections describe options for state management that involve storing information either in the page or on the client computer. For these options, no information is maintained on the server between round trips.
View State
The ViewState [ http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx ] property provides a dictionary object for retaining values between multiple requests for the same page. This is the default method that the page uses to preserve page and control property values between round trips.
When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState [ http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx ] property exceeds the specified value in the MaxPageStateFieldLength [ http://msdn.microsoft.com/en-us/library/system.web.ui.page.maxpagestatefieldlength.aspx ] property. When the page is posted back to the server, the page parses the view-state string at page initialization and restores property information in the page.
You can store values in view state as well. The following example shows how to store a value in the view state.
[Visual Basic]
ViewState("color") = "red"
[C#]
ViewState["color"] = "red";
For more information about using view state, see ASP.NET View State Overview [ http://msdn.microsoft.com/en-us/library/bb386448.aspx ] . For recommendations about when you should use view state, see ASP.NET State Management Recommendations [ http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx ] .
Control State
Sometimes you need to store control-state data in order for a control to work properly. For example, if you have written a custom control that has different tabs that show different information, in order for that control to work as expected, the control needs to know which tab is selected between round trips. The ViewState [ http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx ] property can be used for this purpose, but view state can be turned off at a page level by developers, effectively breaking your control. To solve this, the ASP.NET page framework exposes a feature in ASP.NET called control state.
The ControlState [ http://msdn.microsoft.com/en-us/library/system.web.ui.pagestatepersister.controlstate.aspx ] property allows you to persist property information that is specific to a control and cannot be turned off like the ViewState [ http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx ] property.
The following example shows a custom control that stores a value in control state.
Class Sample
Inherits Control
Dim currentIndex As Integer
Protected Overrides Sub OnInit(ByVal e As EventArgs)
Page.RegisterRequiresControlState(Me)
currentIndex = 0
MyBase.OnInit(e)
End Sub
Protected Overrides Function SaveControlState() As Object
If currentIndex <> 0 Then
Return CType(currentIndex, Object)
Else
Return Nothing
End If
End Function
Protected Overrides Sub LoadControlState(ByVal state As Object)
If (state <> Nothing) Then
currentIndex = CType(state, Integer)
End If
End Sub
End Class
public class Sample : Control {
private int currentIndex = 0;
protected override void OnInit(EventArgs e) {
Page.RegisterRequiresControlState(this);
base.OnInit(e);
}
protected override object SaveControlState() {
return currentIndex != 0 ? (object)currentIndex : null;
}
protected override void LoadControlState(object state) {
if (state != null) {
currentIndex = (int)state;
}
}
}
For more information, see Control State vs. View State Example [ http://msdn.microsoft.com/en-us/library/1whwt1k7.aspx ] .
Hidden Fields
ASP.NET allows you to store information in a HiddenField [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx ] control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls. A hidden field acts as a repository for any page-specific information that you want to store directly in the page.
Security Note: |
|---|
It is easy for a malicious user to see and modify the contents of a hidden field. Do not store any information in a hidden field that is sensitive or that your application relies on to work properly. For more information, see ASP.NET State Management Recommendations [ http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx ] . |
A HiddenField [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx ] control stores a single variable in its Value [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.value.aspx ] property and must be explicitly added to the page. The following example shows a HiddenField [ http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hiddenfield.aspx ] control with an initial value.
<asp:hiddenfield id="ExampleHiddenField"
value="Example Value"
runat="server"/>
For more information, see HiddenField Web Server Control Overview [ http://msdn.microsoft.com/en-us/library/ms227988.aspx ] .
In order for hidden-field values to be available during page processing, you must submit the page using an HTTP POST command. If you use hidden fields and a page is processed in response to a link or an HTTP GET command, the hidden fields will not be available. For usage recommendations, see ASP.NET State Management Recommendations [ http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx ] .
Cookies
A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are saved on the client device, and when the browser requests a page, the client sends the information in the cookie along with the request information. The server can read the cookie and extract its value. A typical use is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your application.
Security Note: |
|---|
The browser can only send the data back to the server that originally created the cookie. However, malicious users have ways to access cookies and read their contents. It is recommended that you do not store sensitive information, such as a user name or password, in a cookie. Instead, store a token in the cookie that identifies the user, and then use the token to look up the sensitive information on the server. |
The following example shows how to write a cookie.
Response.Cookies("destination").Value = "CA"
Response.Cookies("destination").Expires = DateTime.Now.AddDays(1)
Response.Cookies["destination"].Value = "CA";
Response.Cookies["destination"].Expires = DateTime.Now.AddDays(1);
For more information about using cookies, see Cookies [ http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cookies.aspx ] , ASP.NET Cookies Overview [ http://msdn.microsoft.com/en-us/library/ms178194.aspx ] , and ASP.NET State Management Recommendations [ http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx ] .
Query Strings
A query string is information that is appended to the end of a page URL. A typical query string might look like the following example:
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."
Query strings provide a simple but limited way to maintain state information. For example, they are an easy way to pass information from one page to another, such as passing a product number from one page to another page where it will be processed. However, some browsers and client devices impose a 2083-character limit on the length of the URL.
In order for query string values to be available during page processing, you must submit the page using an HTTP GET command. That is, you cannot take advantage of a query string if a page is processed in response to an HTTP POST command. For usage recommendations, see ASP.NET State Management Recommendations [ http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx ] .