ASP.NET Tutorial/Page Lifecycle/ViewState

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

Convert.FromBase64String and view state encoding

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SimpleViewState" %>
<!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:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <asp:Button ID="Button1" OnClick="Button1_Click" runat="server" Text="Button" /></div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 SimpleViewState : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    Label1.Text = "Hello World!";
    }
  protected void Button1_Click(object sender, EventArgs e)
  {
    string viewStateString = "/wEPDwUKLTE2MjY5MTY1NQ9kFgICAw9kFgICAQ8PFgIeBFRleHQFDEhlbGxvIFdvcmxkIWRkZPsbiNOyNAufEt7OvNIbVYcGWHqf";
    
    byte[] stringBytes = Convert.FromBase64String(viewStateString);
    
    string decodedViewState = System.Text.Encoding.ASCII.GetString(stringBytes);
    Label1.Text = decodedViewState;
  }
}


Save string variable to ViewState

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="PreserveMembers" %>
<!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:TextBox ID="txtValue" 
                     runat="server" 
                     Height="160px" 
                     TextMode="MultiLine" 
                     Width="460px">This is a test</asp:TextBox><br />
        <br />
        <asp:Button ID="cmdSave" 
                    runat="server" 
                    OnClick="cmdSave_Click" 
                    Text="Save Contents" />
        <asp:Button ID="cmdLoad" 
                    runat="server" 
                    OnClick="cmdLoad_Click" 
                    Text="Load Contents" /></div>
    </form>
</body>
</html>

File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 PreserveMembers : System.Web.UI.Page
{
  private string contents;
    protected void Page_Load(object sender, EventArgs e)
    {
    if (this.IsPostBack)
    {
      contents = (string)ViewState["contents"];
    }
    }
  protected void Page_PreRender(Object sender, EventArgs e)
  {
    ViewState["contents"] = contents;
  }
  protected void cmdSave_Click(object sender, EventArgs e)
  {
    contents = txtValue.Text;
    txtValue.Text = "";
  }
  protected void cmdLoad_Click(object sender, EventArgs e)
  {
    txtValue.Text = contents;
  }
}


Track Your Viewstate

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 
    Inherits="Default" Theme="Core35-Basic" %>
<!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>Track Your Viewstate</title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="pageContent">
        <asp:Button ID="Button1" runat="server" Text="Post back..." OnClick="Button1_Click" />
        <br />
        <br />
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class Default : System.Web.UI.Page
{
  protected void Page_PreInit(object sender, EventArgs e)
  {
    this.TraceEnabled = true;
  }
    protected void Page_Init(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      this.ViewState["MyData"] = "Hello, world";
    }
    Trace.Warn("[MyData] now contains", (string) ViewState["MyData"]);
  }
  
    protected void Page_Load(object sender, EventArgs e)
  {
    Trace.Warn("[MyData] now contains", (string)ViewState["MyData"]);
  }
}


Use ViewState to create a simple counter (C#)

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SimpleCounter" %>
<!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:Button ID="cmdIncrement" 
                    runat="server" 
                    OnClick="cmdIncrement_Click" 
                    Text="Increment" /><br />
        <br />
        <asp:Label ID="lblCount" runat="server"></asp:Label>&nbsp;</div>
    </form>
</body>
</html>

File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 SimpleCounter : System.Web.UI.Page
{
  protected void cmdIncrement_Click(object sender, EventArgs e)
  {
        int counter;
        if (ViewState["Counter"] == null)
        {
            counter = 1;
        }
        else
        {
            counter = (int)ViewState["Counter"] + 1;
        }
        ViewState["Counter"] = counter;
        lblCount.Text = "Counter: " + counter.ToString();
  }
}


Use ViewState to store random data

<%@ Page Language="C#" AutoEventWireup="true"
 CodeFile="Default.aspx.cs" Inherits="ViewStateChunking" %>
<!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>
        Use View --&gt; Source to see the view
        state of this page.</div>
    </form>
</body>
</html>
File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 ViewStateChunking : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    Random rnd = new Random();
    byte[] buffer = new byte[1050];
    rnd.NextBytes(buffer);
    ViewState["Data"] = buffer;
    }
}


Visualize the current Base64-encoded contents of the view state

<%@ Page Language="C#" AutoEventWireup="true" %>
<!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>Try to Break Your Viewstate</title>
</head>
<script language="javascript">
  function ShowViewState()
  {
    var buf = document.forms[0]["__VIEWSTATE"].value;
    var o = document.forms[0]["ViewStateBox"];
    o.value = buf;
  }
  function UpdateViewState()
  {
    var o = document.forms[0]["ViewStateBox"];
    var viewstate = document.forms[0]["__VIEWSTATE"];
    viewstate.value = o.value;
  }
</script>
<body>
     <form id="form1" runat="server">
        <div id="pageContent">
            <input onclick="ShowViewState()" type="button" value="Display View State" style="width:200px" /> 
            <input onclick="UpdateViewState()" type="button" value="Update View State" style="width:200px" />
            
          <h2>Here"s Your (Encoded) ViewState</h2>
        <asp:TextBox id="ViewStateBox" runat="server" TextMode="MultiLine" Width="100%" Height="250px"></asp:TextBox>
        <asp:Button id="Button1" runat="server" Text="Post Back..."></asp:Button>
        </div>
    </form>
</body>
</html>