ASP.NET ViewState 初探 (2) 轉自msdn

來源:互聯網
上載者:User
asp.net 請看下面的樣本:要在 Web 頁上顯示一個項目列表,而每個使用者需要不同的列表排序。項目列表是靜態,因此可以將這些頁面綁定到相同的快取資料集,而排序次序只是使用者特定的 UI 狀態的一小部分。ViewState 非常適合於儲存這種類型的值。代碼如下:

[Visual Basic]
<%@ Import Namespace="System.Data" %>
<HTML>
    <HEAD>
        <title>用於頁面 UI 狀態值的 ViewState/title>
    </HEAD>
    <body>
        <form runat="server">
            <H3>
                在 ViewState 中儲存非控制項狀態
            </H3>
            <P>
                此樣本將一列待用資料的當前排序次序儲存在 ViewState 中。<br>
                單擊欄位標題中的連結,可按該欄位排序資料。<br>
                再次單擊該連結,將按相反順序排序。
                <br><br><br>
                <asp:datagrid id="DataGrid1" runat="server"
OnSortCommand="SortGrid" BorderStyle="None" BorderWidth="1px"
BorderColor="#CCCCCC" BackColor="White" CellPadding="5" AllowSorting="True">
                    <HeaderStyle Font-Bold="True" ForeColor="White"
BackColor="#006699">
                    </HeaderStyle>
                </asp:datagrid>
            </P>
        </form>
    </body>
</HTML>
<script runat="server">

    ' 在 ViewState 中跟蹤 SortField 屬性
    Property SortField() As String

        Get
            Dim o As Object = ViewState("SortField")
            If o Is Nothing Then
                Return String.Empty
            End If
            Return CStr(o)
        End Get

        Set(Value As String)
            If Value = SortField Then
                ' 與當前排序檔案相同,切換排序方向
                SortAscending = Not SortAscending
            End If
            ViewState("SortField") = Value
        End Set

    End Property

    ' 在 ViewState 中跟蹤 SortAscending 屬性
    Property SortAscending() As Boolean

        Get
            Dim o As Object = ViewState("SortAscending")
            If o Is Nothing Then
                Return True
            End If
            Return CBool(o)
        End Get

        Set(Value As Boolean)
            ViewState("SortAscending") = Value
        End Set

    End Property

    Private Sub Page_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        If Not Page.IsPostBack Then
            BindGrid()
        End If

    End Sub

    Sub BindGrid()

        ' 擷取資料
        Dim ds As New DataSet()
        ds.ReadXml(Server.MapPath("TestData.xml"))
        
        Dim dv As New DataView(ds.Tables(0))

        ' 應用排序過濾器和方向
        dv.Sort = SortField
        If Not SortAscending Then
            dv.Sort += " DESC"
        End If

        ' 綁定網格
        DataGrid1.DataSource = dv
        DataGrid1.DataBind()

    End Sub
    
    Private Sub SortGrid(sender As Object, e As DataGridSortCommandEventArgs)
        DataGrid1.CurrentPageIndex = 0
        SortField = e.SortExpression
        BindGrid()
    End Sub
    
</script>

[C#]
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<HTML>
    <HEAD>
        <title>用於頁面 UI 狀態值的 ViewState</title>
    </HEAD>
    <body>
        <form runat="server">
            <H3>
                在 ViewState 中儲存非控制項狀態
            </H3>
            <P>
                此樣本將一列待用資料的當前排序次序儲存在 ViewState 中。<br>
                單擊欄位標題中的連結,可按該欄位排序資料。<br>
                再次單擊該連結,將按相反順序排序。
                <br><br><br>
                <asp:datagrid id="DataGrid1" runat="server" OnSortCommand="SortGrid"
                BorderStyle="None" BorderWidth="1px" BorderColor="#CCCCCC"
                BackColor="White" CellPadding="5" AllowSorting="True">
                    <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#006699">
                    </HeaderStyle>
                </asp:datagrid>
            </P>
        </form>
    </body>
</HTML>
<script runat="server">

    // 在 ViewState 中跟蹤 SortField 屬性
    string SortField {

        get {
            object o = ViewState["SortField"];
            if (o == null) {
                return String.Empty;
            }
            return (string)o;
        }

        set {
            if (value == SortField) {
                // 與當前排序檔案相同,切換排序方向
                SortAscending = !SortAscending;
            }
            ViewState["SortField"] = value;
        }
    }

    // 在 ViewState 中跟蹤 SortAscending 屬性
    bool SortAscending {

        get {
            object o = ViewState["SortAscending"];
            if (o == null) {
                return true;
            }
            return (bool)o;
        }

        set {
            ViewState["SortAscending"] = value;
        }
    }

    void Page_Load(object sender, EventArgs e) {

        if (!Page.IsPostBack) {
            BindGrid();
        }
    }

    void BindGrid() {

        // 擷取資料
        DataSet ds = new DataSet();
        ds.ReadXml(Server.MapPath("TestData.xml"));
        
        DataView dv = new DataView(ds.Tables[0]);

        // 應用排序過濾器和方向
        dv.Sort = SortField;
        if (!SortAscending) {
            dv.Sort += " DESC";
        }

        // 綁定網格
        DataGrid1.DataSource = dv;
        DataGrid1.DataBind();
   }

   void SortGrid(object sender, DataGridSortCommandEventArgs e) {

        DataGrid1.CurrentPageIndex = 0;
        SortField = e.SortExpression;
        BindGrid();
    }

</script>

下面是上述兩個程式碼片段中引用的 testdata.xml 的代碼:

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <Table>
    <pub_id>0736</pub_id>
    <pub_name>New Moon Books</pub_name>
    <city>Boston</city>
    <state>MA</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>0877</pub_id>
    <pub_name>Binnet & Hardley</pub_name>
    <city>Washington</city>
    <state>DC</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>1389</pub_id>
    <pub_name>Algodata Infosystems</pub_name>
    <city>Berkeley</city>
    <state>CA</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>1622</pub_id>
    <pub_name>Five Lakes Publishing</pub_name>
    <city>Chicago</city>
    <state>IL</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>1756</pub_id>
    <pub_name>Ramona Publishers</pub_name>
    <city>Dallas</city>
    <state>TX</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>9901</pub_id>
    <pub_name>GGG&G</pub_name>
    <city>Muenchen</city>
    <country>Germany</country>
  </Table>
  <Table>
    <pub_id>9952</pub_id>
    <pub_name>Scootney Books</pub_name>
    <city>New York</city>
    <state>NY</state>
    <country>USA</country>
  </Table>
  <Table>
    <pub_id>9999</pub_id>
    <pub_name>Lucerne Publishing</pub_name>
    <city>Paris</city>
    <country>France</country>
  </Table>
</NewDataSet>



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.