asp.net中viewState的应用

来源:互联网 发布:中央办公厅 知乎 编辑:程序博客网 时间:2024/06/05 07:33
  

我们先看网上的一对问答     
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来存取需要暂存的变量和对象了。

 

 

典型应用:查询以后绑定

 

 

 

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>
                &nbsp;&nbsp; 学生姓名<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                &nbsp;&nbsp;&nbsp;&nbsp;<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;
                this.GridView1.DataBind();
            }
        }

 

        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;
            }
            Bind();
        }
    }
}

 

关于ViewState的原理和应用,请参看:http://blog.sina.com.cn/s/blog_67aaf4440100vq0x.html

 

 

 

原创粉丝点击