ここではASP.NETのViewState(ビューステート)の使い方について紹介します。

ViewStateとは

ASP.NETでは、ページを初回表示したときに利用されるPageオブジェクトと、ポストバック時に利用されるPageオブジェクトとは別ものです。ViewStateは、ポストバックの前後でページの状態を保持したい場合に使用します。
ただし、ViewStateはページ自体に保存されるため、大量のデータが保存されると、ポストバック時のオーバーヘッドが増大して送信速度が遅くなる可能性があります。

ViewStateを使用してデータを保存する

以下は WebForm1.aspx の [送信] ボタンをクリックしたらラベルに送信した回数を表示します。

WebForm1.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="Label1" runat="server" Text="送信回数:"></asp:Label>
            <asp:Label ID="Label2" runat="server"></asp:Label>
            <br />
            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="送信" />
        </div>
    </form>
</body>
</html>


VB.NET
WebForm1.aspx.vb

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            ViewState("count") = 0
        End If
    End Sub

    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ViewState("count") = Int32.Parse(ViewState("count").ToString()) + 1
        Label2.Text = $"{ViewState("count")}回"
    End Sub
End Class


C#
WebForm1.aspx.cs

using System;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["count"] = 0;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            ViewState["count"] = Int32.Parse(ViewState["count"].ToString()) + 1;
            Label2.Text = $"{ViewState["count"]}回";
        }
    }
}


以上、ASP.NETのViewState(ビューステート)の使い方について解説しました。