天天看點

asp.net中viewState的應用

我們先看網上的一對問答     

private int x;

protected void Page_Load(object sender, EventArgs e)

{

     if (!IsPostBack)

     {

         x = 1;

     }

}

protected void Button1_Click(object sender, EventArgs e)

     x++;

     Response.Write(x.ToString());

這裡每次調用都輸出1,為什麼不是遞增?如果我想定義在目前頁的變量如何定義。

這是因為x隻是一個局部變量,在一次的網頁請求,等到網頁執行完畢的時候就會被回收,這時候x就已經不存在了,下次再通路的時候又會是一個新的x變量。

除了傳統的Asp中的Session對象外,Asp.net提供了一個更好的ViewState對象。ViewState對象用來儲存頁面中的各種變量,甚至是對象。使用方法和HashTable類似,隻要用變量名稱做索引,如ViewState["Var"],就可以用存取變量Var的值,而不管Var是普通變量,還是對象,甚至是記憶體中的一張DataTable,太友善了。為什麼可以用ViewState而不能用static變量哪?原因就是伺服器端會為每個連接配接到該頁面的使用者分别建立一個ViewState,是以ViewState相當于頁面級的Session。這下我們可以放心地使用ViewState來存取需要暫存的變量和對象了。

典型應用:查詢以後綁定

asp.net中viewState的應用

aspx關鍵代碼

         <tr>

            <td align="center" style="padding-bottom: 20px; font-weight: bold; padding-top: 20px">

                所在院系<asp:DropDownList ID="drpCollege" runat="server" Height="22px" Width="140px">

                </asp:DropDownList>

                   學生姓名<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

                    <asp:Button ID="btnQuery" runat="server" Text="查詢"

                    onclick="btnQuery_Click" />

            </td>

        </tr>

        <tr>

            <td align="center" style="padding-bottom: 20px; padding-top: 20px">

                <br />

                <asp:GridView ID="GridView1" runat="server" DataKeyNames="Num" AllowSorting="true"

                    AutoGenerateColumns="false" CellPadding="5" GridLines="Both" BorderColor="Black"

                    Width="90%">

                </asp>

DAL關鍵代碼:

        public IEnumerable<M_Student> ReadStuByCollegeAndName(String collnum, String name)

        {

            return from s in dc.M_Student

                   where

                       (!String.IsNullOrEmpty(collnum) ? s.CollegeNum.Equals(collnum) : true) &&

                       (!string.IsNullOrEmpty(name) ? s.Name.Contains(name) : true)

                   select s;

        } 

aspx.cs關鍵代碼

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using OnlineTest.Datalinq;

namespace OnlineTest.Manager

    public partial class StudentInfoMaintain : BasePage

    {

        protected void Page_Load(object sender, EventArgs e)

            if (!IsPostBack)

            {

                Bind();

                .......................................

             }

        }

        public void BindGridView(String cnum,String name)

            IEnumerable<M_Student> models = BLL.M_StudentBLL.ReadStuByCollegeAndName(cnum, name);

            if (null != models && 0 != models.Count())

                // 起始條數

                int startRecord = AspNetPager1.PageSize * (AspNetPager1.CurrentPageIndex - 1);

                // 每頁數目

                int maxRecords = AspNetPager1.PageSize;

                // 總數目

                this.AspNetPager1.RecordCount = models.Count();

                this.AspNetPager1.AlwaysShow = true;

                this.GridView1.DataSource = models.Skip(startRecord).Take(maxRecords);

                this.GridView1.DataBind();

            }

            else

                this.GridView1.DataSource = null;

        public void Bind()

            if (null == ViewState["num"])

                ViewState["num"] = "";

            if (null == ViewState["name"])

                ViewState["name"] = "";

            BindGridView(ViewState["num"].ToString(), ViewState["name"].ToString());

        // 分頁事件

        protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)

            this.AspNetPager1.CurrentPageIndex = e.NewPageIndex;

            Bind();

        /// <summary>

        ///  查詢

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        protected void btnQuery_Click(object sender, EventArgs e)

            if(!this.drpCollege.SelectedValue.Equals("0"))

                ViewState["num"] = this.drpCollege.SelectedValue;

            if (!String.IsNullOrEmpty(this.txtName.Text))

                ViewState["name"] = this.txtName.Text;

    }

繼續閱讀