다음을 통해 공유


How to: Save Values in View State

View state is a repository in an ASP.NET page that can store values that need to be retained during postback. View state is typically used for page variables that must be retained rather than user or session data. For example, you can store information in view state that will be accessed during the page load event the next time the page is sent to the server. For usage recommendations, see ASP.NET State Management Recommendations.

View state data is stored in one or more hidden fields as base64-encoded strings. You can access view state information using the page's ViewState property, which exposes a dictionary object. Because the data in view state is stored as a string, only objects that can be serialized can be stored.

Since view state is sent as a hidden field, changes to view state can be made until the PreRenderComplete event. Once the page is rendered to the browser, changes to view state will not be saved.

The information in the hidden view state field can be seen if the page output source is viewed, creating a potential security issue. To mitigate this issue, you can encrypt view state by setting the viewStateEncryptionMode attribute in the @ Page directive to "Always". For more information on security issues with saving information in view state, see Securing View State.

NoteNote

To use the ViewState property, the ASP.NET Web page must have a server form element (<form runat="server">). For usage recommendations, see ASP.NET State Management Recommendations.

This example saves a string and an integer value to view state.

To save a value to view state

  • In page code, set the value of the variable in the ViewState property.

    The following code example shows how to save an ArrayList to view state.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  ' Sample ArrayList for the page.
  Dim PageArrayList As ArrayList

  Function CreateArray() As ArrayList
    ' Create a sample ArrayList.
    Dim result As ArrayList
    result = New ArrayList(4)
    
    result.Add("item 1")
    result.Add("item 2")
    result.Add("item 3")
    result.Add("item 4")
    
    Return result
  End Function
  
  Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If (Me.ViewState("arrayListInViewState") IsNot Nothing) Then
      PageArrayList = CType(Me.ViewState("arrayListInViewState"), ArrayList)
    Else
      ' ArrayList isn't in view state, so we need to load it from scratch.
      PageArrayList = CreateArray()
    End If
    ' Code that uses PageArrayList.
  End Sub
  
  Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    ' Save PageArrayList before the page is rendered.
    Me.ViewState.Add("arrayListInViewState", PageArrayList)
  End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>View state sample</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
  // Sample ArrayList for the page.
  ArrayList PageArrayList;

  ArrayList CreateArray()
  {
    // Create a sample ArrayList.
    ArrayList result = new ArrayList(4);
    
    result.Add("item 1");
    result.Add("item 2");
    result.Add("item 3");
    result.Add("item 4");
    
    return result;
  }

  void Page_Load(object sender, EventArgs e)
  {
    if (ViewState["arrayListInViewState"] != null)
    {
      PageArrayList = (ArrayList)ViewState["arrayListInViewState"];
    }
    else
    {
      // ArrayList isn't in view state, so we need to load it from scratch.
      PageArrayList = CreateArray();
    }
    // Code that uses PageArrayList.
  }
    
  void Page_PreRender(object sender, EventArgs e)
  {
    // Save PageArrayList before the page is rendered.
    ViewState.Add("arrayListInViewState", PageArrayList);
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>View state sample</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

To encrypt view state

  • In the @ Page directive, set the ViewStateEncryptionMode attribute to "Always", as in the following example:

    <% @Page ViewStateEncryptionMode="Always" ...  %>
    

Robust Programming

Only types marked with Serializable can be stored in view state. For more information, see View State Overview.

View state information is stored using base64 encoding and is included in the page during rendering, increasing the size of the page. When the page is posted back, the contents of view state are sent as part of the page postback information. Because view state can significantly increase network traffic and slow down connections, it is recommended that you do not store large quantities of information in view state.

Another important consideration is that if the amount of data in a hidden field becomes large, some proxies and firewalls will prevent access to the page that contains them. Because the maximum amount of data allowed in hidden fields can vary with different firewall and proxy implementations, large hidden fields can cause unpredictable behavior. For more information, see ASP.NET State Management Recommendations.

Some mobile devices do not allow hidden fields at all. Therefore, view state will not work for those devices. For more information, see Understanding State Management.

Security

Information in view state is stored in base-64 format, but it can be tampered with by malicious users. You should treat information stored in view state as user-supplied data and always validate the information before using it. For more information about mitigating view state security risks, see Securing View State. For general information about securing your ASP.NET application, see ASP.NET Web Application Security and Basic Security Practices for Web Applications.

See Also

Tasks

How to: Read Values from View State

Concepts

View State Overview
Securing View State
ASP.NET State Management Overview
ASP.NET State Management Recommendations