Asp.net内置对象—Session对象

Session对象实例—淘宝购物

共需4个页面,main.aspx,a.aspx,b.aspx和c.aspx。

 1.main.aspx效果图:

此页面的C#代码:  protected void Button1_Click(object sender, EventArgs e)

        {

            if (Session["ele"] !=null)          {     this.Label1.Text += Session["ele"].ToString();  }

            if (Session["sport"] != null)      {    this.Label1.Text += Session["sport"].ToString(); }

              if (Session["food"] != null)     {      this.Label1.Text += Session["food"].ToString();}

 2.a.aspx效果图:

后台C#代码:

   protected void Button1_Click(object sender, EventArgs e)      

   {           

  Session["ele"] = "";        

  if (CheckBox1.Checked == true)    { Session["ele"] += this.CheckBox1.Text + ""; }       

  if (CheckBox2.Checked == true)    { Session["ele"] += this.CheckBox2.Text + ""; }            

 if(CheckBox3.Checked==true)       {Session["ele"] +=this.CheckBox3.Text +"";}           

  Response.Redirect("main.aspx");   }

3.b.aspx效果图:

后台C#代码:   protected void Button1_Click(object sender, EventArgs e)   

      {       Session["sport"] = "";            

if (CheckBox1.Checked == true)   { Session["sport"] += this.CheckBox1.Text + ""; }            

 if (CheckBox2.Checked == true)   { Session["sport"]+=this.CheckBox2.Text+"";}            

 if (CheckBox3.Checked == true)  { Session["sport"] += this.CheckBox3.Text + ""; }          

   Response.Redirect("main.aspx");}

4.c.aspx效果图:

后台C#代码:   protected void Button1_Click(object sender, EventArgs e)        

{       Session["sport"] = "";         if (CheckBox1.Checked == true)         { Session["sport"] += this.CheckBox1.Text + ""; }            

                                                  if (CheckBox2.Checked == true)  { Session["sport"]+=this.CheckBox2.Text+"";}           

                                                 if (CheckBox3.Checked == true)   { Session["sport"] += this.CheckBox3.Text + ""; }       

                                                 Response.Redirect("main.aspx");

}

总结:

1.Session对象用来保存一次回话中的客户的信息,存储在客户端和服务端,客户端只负责保存相应网站的SessionId,其他信息保存在服务器端,这就是说session安全的原因。 

2.语法类似Application; Session["名称"]=变量/字符串/表达式;

3.与cookies的expires属性非常相似,session也有一个timeout属性,它的作用也是个有效期,session对象保存客户信息默认时间是20分钟。超过则seesion对象失效。

eg:Session.Timeout=90; (单位默认为分钟;此例为网上考试时一般会把session对象有效期改为为90分钟)

posted @ 2012-03-13 15:53  zhangmengjie  Views(269)  Comments(0)    收藏  举报