ASP.NET Tutorial/Sessions/ViewState

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Disable ViewState for a certain control

<%@ 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">
    Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
        Label1.Text = (Int32.Parse(Label1.Text) + 1).ToString()
        Label2.Text = (Int32.Parse(Label2.Text) + 1).ToString()
    End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Disable View State</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    Label 1:
    <asp:Label
        id="Label1"
        EnableViewState="false"
        Text="0"
        Runat="server" />
    <br />
    Label 2:
    <asp:Label
        id="Label2"
        Text="0"
        Runat="server" />
    
    <br /><br />
    
    <asp:Button
        id="btnAdd"
        Text="Add"
        OnClick="btnAdd_Click" 
        Runat="server" />
    
    </div>
    </form>
</body>
</html>


Insert view state data in Page render event (C#)

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ViewState["Example"] = "nfex.ru";
    }
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
        base.Render(htmlWriter);
        string html = stringWriter.ToString();
        int StartPoint = html.IndexOf("<input type=\"hidden\" name=\"__viewstate\"");
        if (StartPoint >= 0)
        {
            int EndPoint = html.IndexOf("/>", StartPoint) + 2;
            string viewstateInput = html.Substring(StartPoint, EndPoint - StartPoint);
            html = html.Remove(StartPoint, EndPoint - StartPoint);
            int FormEndStart = html.IndexOf("</form>") - 1;
            if (FormEndStart >= 0)
            {
                html = html.Insert(FormEndStart, viewstateInput);
            }
        }
        writer.Write(html);
    }

}


Insert view state data in Page render event (VB)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.vb
Imports System.IO
Partial Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ViewState("Example") = "nfex"
    End Sub

    Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
        Dim stringWriter As System.IO.StringWriter = New System.IO.StringWriter
        Dim htmlWriter As HtmlTextWriter = New HtmlTextWriter(stringWriter)
        MyBase.Render(htmlWriter)
        Dim html As String = stringWriter.ToString
        Dim StartPoint As Integer
        StartPoint = html.IndexOf("<input type=\""hidden\"" name=\""__viewstate\""")
        If (StartPoint >= 0) Then
            Dim EndPoint As Integer = (html.IndexOf("/>", StartPoint) + 2)
            Dim viewstateInput As String
            viewstateInput = html.Substring(StartPoint, (EndPoint - StartPoint))
            html = html.Remove(StartPoint, (EndPoint - StartPoint))
            Dim FormEndStart As Integer = (html.IndexOf("</form>") - 1)
            If (FormEndStart >= 0) Then
                html = html.Insert(FormEndStart, viewstateInput)
            End If
        End If
        writer.Write(html)
    End Sub

End Class


Trim view state

<%@ Page Language="C#" 
         AutoEventWireup="true"  
         CodeFile="Default.aspx.cs" 
         Inherits="TrimViewState" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
               "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="lstBig" runat="server" EnableViewState="False"/>
        <asp:Button ID="cmdSubmit" runat="server" OnClick="cmdSubmit_Click" Text="Button" />
        <asp:Label ID="lblInfo" runat="server" Text=""/>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class TrimViewState : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    for (int i = 0; i < 1000; i++)
    {
      lstBig.Items.Add(i.ToString());
    }
    if (Page.IsPostBack)
    {
      lstBig.SelectedItem.Text = Request.Form["lstBig"];
    }
    }
  protected void cmdSubmit_Click(object sender, EventArgs e)
  {
    lblInfo.Text += lstBig.SelectedItem.Text + "<br />";
    //lblInfo.Text = Request.Form["lstBig"];
  }
}


Use ViewState to store object list (C#)

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page 
{
    [Serializable]
    class Person
    {
        public string first = "first";
        public string last = "last";
        public string blog = "http://www.nfex.ru";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Person[] people = new Person[500];
        for (int i = 0; i < people.Length; i++)
        {
            people[i] = new Person();
        }
        ViewState["Folks"] = people;
    }
    private string _pageGuid = null;
    public string PageGuid
    {
        get
        {
            if (_pageGuid == null)
                _pageGuid = this.Request.Form["__VIEWSTATE_KEY"];
            if (_pageGuid == null)
                _pageGuid = Guid.NewGuid().ToString();
            return _pageGuid;
        }
        set
        {
            _pageGuid = value;
        }
    }
    protected override object LoadPageStateFromPersistenceMedium()
    {
        return Session[this.PageGuid];
    }
    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        RegisterHiddenField("__VIEWSTATE_KEY", this.PageGuid);
        Session[this.PageGuid] = viewState;
    }
}


Use ViewState to store object list (VB)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.vb

Partial Class _Default
    Inherits System.Web.UI.Page
    <Serializable()> Class Person
        Public first As String = "first"
        Public last As String = "last"
        Public blog As String = "http://www.nfex.ru"
    End Class
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim people(500) As Person
        For i As Integer = 0 To people.Length - 1 Step 1
            people(i) = New Person
        Next
        ViewState("Folks") = people
    End Sub
    Dim _pageGuid As String = Nothing
    Public Property PageGuid() As String
        Get
            "Do we have it already? Check the Form, this could be a post back
            If (_pageGuid = Nothing) Then
                _pageGuid = Me.Request.Form("__VIEWSTATE_KEY")
            End If
            "No? We"ll need one soon.
            If (_pageGuid = Nothing) Then
                _pageGuid = Guid.NewGuid.ToString
            End If
            Return _pageGuid
        End Get
        Set(ByVal value As String)
            _pageGuid = value
        End Set
    End Property
    Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
        Return Session(Me.PageGuid)
    End Function
    Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)
        RegisterHiddenField("__VIEWSTATE_KEY", Me.PageGuid)
        Session(Me.PageGuid) = viewState
    End Sub

End Class