ASP.NET学习笔记

来源:互联网 发布:java图像局部虚化 编辑:程序博客网 时间:2024/05/17 07:43

采用.NET Framework 3.5


1.新建网站

单击"文件"->"新建"->"网站"命令

位置处选择文件系统

"文件系统"指网站的文件放在本地硬盘或放在一个局域网上的一个共享位置。对网站的开发,运行和调试都无需IIS支持,而使用内置的ASP.NET Development Server Web服务器。

新建完成后出现

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">    <div>    Hello World    </div>    </form></body></html>

如上程序在<div></div>之间写上Hello World按Ctrl+F5运行程序

在网页上会看到Hello World 


2.学习ASP.NET需要先掌握Html,CSS,JS,XML,C#,等


3.在ASP.NET 3.5中web窗体都是.aspx文件,而C#文件的后缀是.cs

 在web窗体中有两种模型

单文件页模型:

在单文件页模型中,显示代码和逻辑处理代码都放在同一个.asp文件中

此时C#其实扮演的是一种脚本语言的角色

代码隐藏页模型:

在此模型中显示也界面都放在.asp文件中。而逻辑处理代码(C#代码)放在.cs文件中


4.标准控件

常用的事件

Page_PreInit(页面预初始化)

Page_Init(页面初始化)

Page_Load(页面加载)

控件事件(如:Button控件的Click事件)

从上到下依次为事件的处理顺序

Click事件被触发会引起页面的往返处理。

Change事件触发时,现将信息暂存在客户的缓冲区中,等到下一次向服务器传递消息时,在和其他信息一起发到服务器(但修改属性AutoPostBack的值为true时可立即响应,但这种设置会降低效率。)


属性IsPostBack

Page的IsPostBack属性在用户第一次浏览网页时,会返回值false,否则返回true

例子:

.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">    <div>            <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="刷新网页" />        </div>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class _Default : System.Web.UI.Page {    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            Response.Write("页面第一次加载!");        }    }    protected void Button1_Click(object sender, EventArgs e)    {        Response.Write("执行了Click事件代码");    }}

程序只有刚运行时显示页面第一次加载,后来都不显示


Label控件

Label控件用于在浏览器上显示文本。

Label控件中的属性AssociatedControlId,它的值可把Label控件与窗体中另一个服务器控件关联起来。(注:associated:关联)

例题:通过快捷键激活文本框

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Label.aspx.cs" Inherits="Label" %><!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="lblName" runat="server" AccessKey="N" AssociatedControlID="txtName" Text="用户名(N)"></asp:Label>        :<asp:TextBox ID="txtName" runat="server"></asp:TextBox>        <br />        <br />        <asp:Label ID="lblPassword" runat="server" AccessKey="P" AssociatedControlID="txtPassword" Text="密码(P)"></asp:Label> :<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>        </div>    </form></body></html>


TextBox控件

TextBox控件显示数据或输入数据。

TextBox控件常用的属性,方法和事件

TextMOde属性(值SingleLine表示单行文本框;值Password表示密码框;MultiLine表示多行文本框)

AutoPostBack属性(值true表示当文本框内容改变且焦点移出文本框时触发TextChanged事件,引起页面往返处理)

AutoCompleteType属性(标注能自动完成的类型)

Focus()方法(设置文本框焦点)

TextChanged事件(当文本框内容且焦点离开文本框后触发)

例题:

.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TextBox.aspx.cs" Inherits="TextBox" %><!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:TextBox ID="txtName" runat="server" AutoPostBack="True" OnTextChanged="txtName_TextChanged"></asp:TextBox>        <asp:Label ID="lblValidate" runat="server"></asp:Label>        <br />        密  码:<asp:TextBox ID="TextBox1" runat="server" TextMode="Password"></asp:TextBox>        <br />        E-mail:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>        <br />        <asp:Button ID="Button1" runat="server" Text="确定" />        </div>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class TextBox : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        txtName.Focus();    }    protected void txtName_TextChanged(object sender, EventArgs e)    {        if (txtName.Text == "jxssg")        {            lblValidate.Text = "用户名已占用!";        }        else        {            lblValidate.Text = "用户名正确";        }    }}

Button , LinkButton和ImageButton控件

Button呈现传统按钮外观;LinkButton呈现超链接外观;ImageButton呈现图形外观,其图像有ImageUrl属性设置(相当于html元素中的<a>元素)。

常用属性和方法:

PostBackUrl属性(单击按钮时发送到的URL)

Click事件(单击时触发,执行服务器代码)

ClientClick事件(单击时触发,执行客户端代码)

例题:在单击Button控件后执行客户端脚本,提示删除点击确定后提示删除成功

.aspx代码

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">    <div>            <asp:Button ID="Button1" runat="server" Text="删除"             OnClientClick="return confirm('确认要删除记录吗?')" OnClick="Button1_Click"             />        </div>    </form></body></html>
代码中
OnClientClick="return confirm('确认要删除记录吗?')"为手工输入。


DropDownList控件(下拉列表控件)

常用的属性,方法,和事件

DataSource属性(使用的数据源)

DataTextField属性(对应数据源中的一个字段,该字段所有内容显示在下拉列表中)

DataValueField属性(数据源中的一个字段,指定下拉列表中每个可选项的值)

Items属性(列表中所有选项的集合,经常使用Items.Add()方法添加项,Clear()方法删除所有项)

SelectedItem属性(当前选定项)

SelectValue属性(当前选定项的Value值)

SelectedIndexChanged事件(当选择下拉列表中一项后被触发)

DataBind()方法(绑定数据源)


在DropDownList中,添加项的方式有三种

第一种在在窗口中直接对属性进行设置


如图:点击编辑项进入集合编辑器窗体。点击添加设置Test和Value即可

第二种方法是利用DropDownList对象的Items.Add()方法添加项,如:

DropDownList1.Items.Add(new ListItem("浙江","zhejiang"));
此代码放在.cs文件中

第三种方法通过DataSource设置数据源,在通过DataBind(),方法显示数据(在后边会详细讲解)

实例:以日期联动为例

.aspx代码

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">    <div>            <asp:DropDownList ID="ddlYear" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" Width="77px">        </asp:DropDownList>        年<asp:DropDownList ID="ddlMonth" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged" Width="47px">        </asp:DropDownList>        月<asp:DropDownList ID="ddlDay" runat="server" Width="50px">        </asp:DropDownList>        日</div>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class _Default : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        //页面第一次载入,向各下拉列表填充值        if (!IsPostBack)        {            BindYear();            BindMonth();            BindDay();        }    }    protected void BindYear()    {        //清除年份下拉列表中项        ddlYear.Items.Clear();        int startYear = DateTime.Now.Year - 10;        int currentYear = DateTime.Now.Year;        //向年份下拉列表中添加新项        for (int i = startYear; i <= currentYear; i++)        {            ddlYear.Items.Add(new ListItem(i.ToString()));        }        //设置年份下拉列表默认项        ddlYear.SelectedValue = currentYear.ToString();    }    protected void BindMonth()    {        ddlMonth.Items.Clear();        //向月份下拉列表添加项        for (int i = 1; i <= 12; i++)        {            ddlMonth.Items.Add(i.ToString());        }    }    protected void BindDay()    {        ddlDay.Items.Clear();        //获取年份下拉列表选中值        string year = ddlYear.SelectedValue;        string month = ddlMonth.SelectedValue;        //获取相应的年和月对应的值        int datys = DateTime.DaysInMonth(int.Parse(year), int.Parse(month));        //向下拉列表中添加新项        for (int i = 1; i < datys; i++)        {            ddlDay.Items.Add(i.ToString());        }    }    protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)    {        BindDay();    }    protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)    {        BindDay();    }}

ListBox控件

ListBox的选项列表是可见的。并且可同时选择多项(当属性SelectionMode的值为Multiple时表示允许选择多项)注:multipel  :多重的,多样的

实例:实现数据在ListBox控件之间的移动

运行效果:


ListBox.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListBox.aspx.cs" Inherits="ListBox" %><!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:ListBox ID="lstLeft" runat="server" Height="140px" Rows="5" SelectionMode="Multiple" Width="60px">                <asp:ListItem Value="hunan">湖南</asp:ListItem>                <asp:ListItem Value="shanghai">上海</asp:ListItem>                <asp:ListItem Value="nanjing">南京</asp:ListItem>                <asp:ListItem Value="jiangxi">江西</asp:ListItem>                <asp:ListItem Value="beijing">北京</asp:ListItem>            </asp:ListBox>            <asp:Button ID="btnMove" runat="server" Style="font-size: large; position: relative; top: -55px; left: 4px" Text=">" OnClick="btnMove_Click" />            <asp:ListBox ID="lstRight" runat="server" Height="140px" Rows="5" SelectionMode="Multiple" Width="60px" Style="position: relative; top: 3px; left: 12px; font-size: large; margin-right: 0px"></asp:ListBox>        </div>    </form></body></html>
.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class ListBox : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void btnMove_Click(object sender, EventArgs e)    {        //遍历左边列表框中的所有项        for (int i = 0; i < lstLeft.Items.Count; i++)        {            //判断项是否选中            if (lstLeft.Items[i].Selected)            {                //向右边列表框添加选中的一项                lstRight.Items.Add(lstLeft.Items[i]);                lstLeft.Items.Remove(lstLeft.Items[i]);            }        }    }}

CheckBox和CheckBoxList控件

这两种控件常做复选框的作用。

当需要多项选择时,可以选择多个CheckBox或单个CheckBoxList(一般采用CheckBoxList)

注意:在实际应用中一般设置CheckBoxList的属性值AutoPost值为false。也就是说提交数据到服务器,不采用CheckBoxList的自身事件,而是配合Button控件实现。

实例:运行效果


.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CheckBoxList.aspx.cs" Inherits="CheckBoxList" %><!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:CheckBoxList ID="chklsSport" runat="server" Style="font-size: large">                <asp:ListItem Value="football">足球</asp:ListItem>                <asp:ListItem Value="basketball">篮球</asp:ListItem>                <asp:ListItem Value="badminton">羽毛球</asp:ListItem>                <asp:ListItem Value="pingpong">乒乓球</asp:ListItem>            </asp:CheckBoxList>        </div>        <asp:Button ID="btnSubmit" runat="server" Text="确认" Stryle="font-size:large" OnClick="btnSubmit_Click" />        <asp:Label ID="lblMsg" runat="server" style="font-size:large" ></asp:Label>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class CheckBoxList : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void btnSubmit_Click(object sender, EventArgs e)    {        lblMsg.Text = "你选择了";        //遍历复选框中所有项        foreach (ListItem item in chklsSport.Items)        {            if (item.Selected)            {                lblMsg.Text = lblMsg.Text + item.Text + " ";            }        }    }}



RadioButton和RadioButtonList控件

这两种控件其实都是单选按钮(用于多选一)

RadioButton只能提供单项选择,也可以多个RadioButton形成一组,方法是设置每个RadioButton的属性GroupName为同一个名称。

定义RadioButton的语法格式如下:

<asp:RadioButton ID="RadioButton1" runat="server" GroupName="group" />        <asp:RadioButton ID="RadioButton2" runat="server" GroupName="group" />

定义RadioButtonList的语法格式如下:

    <asp:RadioButtonList ID="RadioButtonList1" runat="server">            <asp:ListItem>男</asp:ListItem>            <asp:ListItem>女</asp:ListItem>        </asp:RadioButtonList>
主意:判断RadionButton是否选中使用Checked属性,而获取RadioButtonList的选中项用属性SelectedItem。


Image和ImageMap控件

Image控件图片源文件可以使用ImageUrl属性在界面设计时确定,也可以在编程时指定,或和数据源绑定。

Image控件不包含Click事件,如果需要Click事件处理流程。可使用ImageButton控件代替Image控件。


ImageMap可以将显示的图片划分为不同形状的热点区域,分别连接到不同的页面。(常用做导航条,地图等)

热点区域通过HotSpot设置,划分区域有圆形CircleHotSpot,长方形RectangleHotSpot和任意多边形PolygonHotSpot,每个区域通过属性NavigateUrl确定要链接的URL。




HyperLink控件

HyperLink控件用于在网页上创建链接,于元素<a>不同,它可以于数据源绑定。

HyperLink控件不包含Click事件,要使用Click事件可用LinkButton控件代替。

使用属性ImageUrl可以将链接设置为一副图片。在同时设置了属性Text和ImageUrl的情况下,ImageUrl优先。若找不到图片则显示属性Text设置的内容。

在HyperLink中直接设置ImageUrl后显示的图形尺寸是不可调的,若要改变图形尺寸,可配合使用Image控件。


Table控件

Table控件是一种容器控件。

Table对象由行(TableRow)对象组成,Table对象由单元格(TableCell)对象组成。

实例:动态生成表格

运行效果:


.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="haha.aspx.cs" Inherits="haha" %><!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">        <asp:Table ID="tblScore" runat="server" GridLines="Both">            <asp:TableRow runat="server">                <asp:TableCell runat="server">学号</asp:TableCell>                <asp:TableCell runat="server">姓名</asp:TableCell>                <asp:TableCell runat="server">成绩</asp:TableCell>            </asp:TableRow>        </asp:Table>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class haha : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        //设置初始值,实际项目中数据源来源于数据库        String[] number = { "140112003", "140112004" };        String[] name = { "张三", "李四" };        //动态生成表格        for (int i = 1; i <= 2; i++)        {            //建立一个行对象            TableRow row = new TableRow();            //建立一个单元格对象            TableCell cellNumber = new TableCell();            //建立第二个单元格对象            TableCell cellName = new TableCell();            //建立第三个单元格            TableCell cellInput = new TableCell();            //设置第一个单元格的的属性Text            cellNumber.Text = number[i - 1];            cellName.Text = number[i - 1];            //建立一个文本框对象            TextBox txtInput = new TextBox();            //将文本框对象添加到第三个单元格中            cellInput.Controls.Add(txtInput);            row.Cells.Add(cellNumber);            row.Cells.Add(cellName);            row.Cells.Add(cellInput);            //添加行对象到表格对象            tblScore.Rows.Add(row);        }    }}


Panel和PlaceHolder控件

这两个控件都是容器空控件

Panel控件把包含在其中的控件组成当成一个整体看待

实例:使用Panel实现简单注册页面

运行效果:


.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Panel.aspx.cs" Inherits="Panel" %><!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:Panel ID="pnlStep1" runat="server">                第一步:输入用户名<br /> 用户名:<asp:TextBox ID="txtUser" runat="server"></asp:TextBox>                <br />                <asp:Button ID="btnStep1" runat="server" OnClick="btnStep1_Click" Text="下一步" />            </asp:Panel>        </div>        <asp:Panel ID="pnlStep2" runat="server">            第二步:输入用户信息<br /> 姓名:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>            <br />            电话:<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>            <br />            <asp:Button ID="btnStep2" runat="server" OnClick="btnStep2_Click" Text="下一步" />        </asp:Panel>        <asp:Panel ID="pnlStep3" runat="server">            第三步:请确认你输入的信息<br />             <asp:Label ID="lblMsg" runat="server"></asp:Label>            <br />            <asp:Button ID="btnStep3" runat="server" OnClick="btnStep3_Click" Text="确认" />        </asp:Panel>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Panel : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            pnlStep1.Visible = true;            pnlStep2.Visible = false;            pnlStep3.Visible = false;        }    }    protected void btnStep1_Click(object sender, EventArgs e)    {        pnlStep1.Visible = false;        pnlStep2.Visible = true;        pnlStep3.Visible = false;    }    protected void btnStep2_Click(object sender, EventArgs e)    {        pnlStep1.Visible = false;        pnlStep2.Visible = false;        pnlStep3.Visible = true;        //输出用户信息        lblMsg.Text = "用户名:" + txtUser.Text + "<br />姓名:" + txtName.Text + "<br />电话:" + txtTelephone.Text;    }    protected void btnStep3_Click(object sender, EventArgs e)    {        //将用户信息保存到数据库    }}

实例:利用PlaceHolder动态添加控件

.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PlaceHolder.aspx.cs" Inherits="PlaceHolder" %><!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:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>        <br />        <asp:Button ID="btnAcquire" runat="server" OnClick="btnAcquire_Click" Text="获取" />        </div>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class PlaceHolder : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        //定义按钮控件btnSubmit        Button btnSubmit = new Button();        btnSubmit.ID = "btnSubmit";        btnSubmit.Text = "确认";        //注册Click事件        btnSubmit.Click += new EventHandler(btnSubmit_Click);        //将btnSubmit控件添加到PlaceHolder1中        PlaceHolder1.Controls.Add(btnSubmit);        //定义文本框控件txtInput        TextBox txtInput = new TextBox();        txtInput.ID = "txtInput";        PlaceHolder1.Controls.Add(txtInput);    }    protected void btnAcquire_Click(object sender, EventArgs e)    {        //查找txtInput控件        TextBox txtInput = (TextBox)PlaceHolder1.FindControl("txtInput");        Response.Write(txtInput.Text);    }    private void btnSubmit_Click(object sender, EventArgs e)    {        Response.Write("触发了动态生成控件中按钮事件");    }}

MultiView和View控件

在使用时MultiView做为View的容器控件,View作为作为其它控件的容器控件。

MultiView的属性ActiveViewIndex决定了当前显示哪个视图,默认值为-1,值0表示MultiView中包含的第一个View,以此类推。

为了在多个View之间切换,需要在View中添加Button类型控件,如Button,LinkButton,ImageButton。

View中button类型控件实用属性

CommandNameCommandArgument说明NextView不需要设置显示下一个ViewPrevView不需要设置显示上一个ViewSwitchViewByID要切换到View控件的ID切换到指定ID的ViewViewByIndex要切换到View控件索引号切换到指定索引好的View实例:

.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiView.aspx.cs" Inherits="MultiView" %><!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:MultiView ID="mvSurvey" runat="server">            <asp:View ID="View1" runat="server">                1.您从事的是哪种应用程序的编程?<br />                 <asp:RadioButtonList ID="rdoltView1" runat="server">                    <asp:ListItem Value="webapp">Web应用程序</asp:ListItem>                    <asp:ListItem Value="winapp">Windows应用程序</asp:ListItem>                </asp:RadioButtonList>                <asp:Button ID="btnView1Next" runat="server" Text="下一个" CommandName="NextView" />                <br />             </asp:View>            <asp:View ID="View2" runat="server">2.您最常用的语言是哪一种<br />                 <asp:RadioButtonList ID="rdoltView2" runat="server">                    <asp:ListItem Value="cshap">C#语言</asp:ListItem>                    <asp:ListItem>Java</asp:ListItem>                </asp:RadioButtonList>                <asp:Button ID="btnView2Prew" runat="server" CommandName="PreView" Text="上一个" />                <asp:Button ID="btnView2Next" runat="server" CommandName="NextView" OnClick="btnView2Next_Click" Text="下一个" />            </asp:View>            <asp:View ID="View3" runat="server">谢谢您的参与!<br />                 <asp:Label ID="lblDisplay" runat="server"></asp:Label>                <br />                <asp:Button ID="btnSave" runat="server" Text="保存" />            </asp:View>        </asp:MultiView>        </div>    </form></body></html>

.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class MultiView : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        if (!IsPostBack)        {            //显示第一个活动视图            mvSurvey.ActiveViewIndex = 0;        }    }    protected void btnView2Next_Click(object sender, EventArgs e)    {        lblDisplay.Text = "您选择了:" + "<br />" + rdoltView1.SelectedItem.Text + "<br />" + rdoltView2.SelectedItem.Text;    }}


Wizard控件

Wizard控件做为一种向导控件,主要用于搜集用户信息,配置系统等。

实例:利用Wizard控件实现用户编程习惯调查

操作步骤:

(1)新建一个.aspx文件,在设计视图中添加一个Wizard控件

(2)单击Wizard控件的智能标记,再单击"添加/移除WizardSteps",然后分别添加WizardStep并设置属性




其中程序语言的StepType属性设置为Step

(3)单击"编辑模版",选择HeaderTemplate,输入"用户编辑习惯调查"。最后单击"结束模版编辑"选项。


(4)单击Wizard控件中的"程序类型",添加一个RadioButtonList控件。


同理单击“程序设计语言”,单击“完成”。完成以上设置,再补充代码

(5)Wizard可以套用样式选中Wizard控件右键,再点击自动套用格式。选择合适的格式。


运行效果图:


整体代码如下:.aspx代码

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><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:Wizard ID="Wizard1" runat="server" ActiveStepIndex="1" OnNextButtonClick="Wizard1_NextButtonClick" OnFinishButtonClick="Wizard1_FinishButtonClick" BackColor="#FFFBD6" BorderColor="#FFDFAD" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em">            <HeaderStyle BackColor="#FFCC66" BorderColor="#FFFBD6" BorderStyle="Solid" BorderWidth="2px" Font-Bold="True" Font-Size="0.9em" ForeColor="#333333" HorizontalAlign="Center" />            <HeaderTemplate>                用户编程习惯调查            </HeaderTemplate>            <NavigationButtonStyle BackColor="White" BorderColor="#CC9966" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#990000" />            <SideBarButtonStyle ForeColor="White" />            <SideBarStyle BackColor="#990000" Font-Size="0.9em" VerticalAlign="Top" />            <WizardSteps>                <asp:WizardStep runat="server" StepType="Start" title="程序类型">                    <asp:RadioButtonList ID="RadioButtonList1" runat="server">                        <asp:ListItem>Web程序</asp:ListItem>                        <asp:ListItem>Windows应用程序</asp:ListItem>                    </asp:RadioButtonList>                </asp:WizardStep>                <asp:WizardStep runat="server" StepType="Step" title="程序语言">                    <asp:RadioButtonList ID="RadioButtonList2" runat="server">                        <asp:ListItem>C#</asp:ListItem>                        <asp:ListItem>Java</asp:ListItem>                    </asp:RadioButtonList>                </asp:WizardStep>                <asp:WizardStep runat="server" StepType="Finish" Title="完成">                    <asp:Label ID="labDisplay" runat="server"></asp:Label>                </asp:WizardStep>            </WizardSteps>        </asp:Wizard>        </div>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class _Default : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)    {        if (Wizard1.ActiveStepIndex == 1)        {            labDisplay.Text = "程序类型:" + RadioButtonList1.SelectedValue + "<br />程序语言:" + RadioButtonList2.SelectedValue;        }    }    protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)    {        Response.Write("保存数据成功!");    }}



5.服务器验证控件


验证不能保证输入信息的真实性,但可以令其满足一些规则。

窗体验证分为服务器端(比较慢,但安全)和客户端(比较快,不安全)两种形式。

ASP.NET的服务器验证控件可以自动的检测浏览器是否支持JavaScript,如果支持,则进行客户端验证,否则在服务器端执行验证


ASP.NET 3.5有六个验证控件:RequiredFieldValidator (必填项验证), CompareValidator(比较验证) , RangeValidator(范围验证) , RegularExpressionValidator , CustomValidator , ValidationSummary(确认概要)控件。

前五个控件共同具有的常用属性如下表所示

属性说明ControlToValidate指定要验证的控件IDDisplay指定验证控件在页面上显示的方式。
值Static(表示验证控件始终占用页面空间);
值Dynamic(表示控件有错误时才占用页面空间);
值None(表示验证控件的错误信息都在ValidationSummary中显示)。EnableClientScript设置是否启用客户端验证,默认值true(客户端验证的JavaScript代码系统自己会产生)ErrorMessage设置在ValidationSummary控件中显示错误信息,若属性Text值为空可代替Text的作用SetFocusOnError当验证无效时,确定是否将焦点定位到验证控件中Text设置验证控件显示信息ValidationGroup设置验证控件分组名

如果页面有验证控件,但页面的一次往返却不想进行验证,如"取消"按钮。

则可以通过设置按钮的属性CasesValidation的值为false就可以了。


RequiredFieldValidator控件

此控件对于一些必填的信息进行检验

如:第一条语句表示txtName不能为空,第二句表示txtName的内容不能和"您的姓名"相同。

<asp:RequiredFieldValidator ID="rfvName1" runat="server" ControlToValidate="txtName" ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator><asp:RequiredFieldValidator ID="rfvName2" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="txtName" InitialValue="您的姓名" Text="不能和初始值相同"></asp:RequiredFieldValidator>

CompareValidator控件

此控件用于比较一个控件和另一个控件的值。相等通过,否则不通过。

常用属性表

属性说明ControlToCompare指定于被验证控件比较的控件IDOperator设置比较时使用的操作符。值包括Equal , NotEqual , GreaterThan
GreaterThanEqual , LessThan , LessThanEqual , DataTypeCheckType设置比较值时使用的数据类型ValueToCompare指定于被验证控件的比较值

属性ControlToCompare和ValueToCompare应用时只能选择一个。

实例:运行效果


.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Compare.aspx.cs" Inherits="Compare" %><!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:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>        <br />        确 认 密 码:<asp:TextBox ID="txtPasswordAgain" runat="server" TextMode="Password"></asp:TextBox>        <asp:CompareValidator ID="cvPassword" runat="server" ControlToCompare="txtPassword" ControlToValidate="txtPasswordAgain" ErrorMessage="密码与确认密码不一致"></asp:CompareValidator>        <br />        答    案:<asp:TextBox ID="txtAnswer" runat="server"></asp:TextBox>        <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtAnswer" ErrorMessage="答案错误" ValueToCompare="A"></asp:CompareValidator>        <br />        金    额:<asp:TextBox ID="txtAmount" runat="server"></asp:TextBox>        <asp:CompareValidator ID="cvAmount" runat="server" ControlToValidate="txtAmount" ErrorMessage="必须填入Currency类型!" Operator="DataTypeCheck" Type="Currency"></asp:CompareValidator>        </div>    </form></body></html>


RangeValidator控件

此控件通过属性MaximumValue和MinimumValue,分别对应验证范围的最大值和最小值。


RegularExpressionValidator控件

此控件用来验证输入值是否和正则表达式相匹配,常用来验证电话号,邮政编码,E-mail等。

常通过ValidationExpression来确定要检验的正则表达式。


CustomValidator控件

此控件为用户自定义控件。

CustomValidator控件如果使用客户端验证,则需要设置属性ClientValidationFunciton值为客户端检验函数名,并且要设置EnableClientScript的值为true;

若使用服务器端验证,则通过事件ServerValidate触发。


ValidationSummary控件

此控件汇总了其他验证控件错误信息,即汇总了其他控件的属性ErrorMessage值。

ValidationSummary控件的属性DisplayMode指定了显示信息的格式,值分别为BulletList , List , SingleParagraph。属性ShowMessageBox指定了是否在弹出一个消息框中显示错误信息。属性ShowSummary指定是否启用错误信息汇总。

综合实例:运行效果


.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MultiValidate.aspx.cs" Inherits="MultiValidate" %><!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:TextBox ID="txtName" runat="server"></asp:TextBox>            <asp:RequiredFieldValidator ID="rfvName" runat="server" ControlToValidate="txtName" ErrorMessage="输入用户名!" SetFocusOnError="True"></asp:RequiredFieldValidator>        <br />        密  码:<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>        <asp:RequiredFieldValidator ID="rfvPassword" runat="server" ControlToValidate="txtPassword" ErrorMessage="请输入密码!" SetFocusOnError="True"></asp:RequiredFieldValidator>        <br />        确认密码:<asp:TextBox ID="txtPasswordAgain" runat="server"></asp:TextBox>        <asp:RequiredFieldValidator ID="rfvPasswordAgain" runat="server" ControlToValidate="txtPasswordAgain" ErrorMessage="请输入确认密码!" SetFocusOnError="True"></asp:RequiredFieldValidator>        <asp:CompareValidator ID="cvPassword" runat="server" ControlToCompare="txtPassword" ControlToValidate="txtPasswordAgain" ErrorMessage="密码与确认密码不一至!" SetFocusOnError="True"></asp:CompareValidator>        <br />        电话号码:<asp:TextBox ID="txtTelephone" runat="server"></asp:TextBox>        <asp:RequiredFieldValidator ID="rfvTelephone" runat="server" ControlToValidate="txtTelephone" ErrorMessage="请输入电话号码!" SetFocusOnError="True">*</asp:RequiredFieldValidator>        <asp:RegularExpressionValidator ID="revTelephone" runat="server" ControlToValidate="txtTelephone" ErrorMessage="电话号码格式应为83642378" SetFocusOnError="True" ValidationExpression="(\(\d{3}\)|\d{3}-)?\d{8}"></asp:RegularExpressionValidator>        <br />        身份证号:<asp:TextBox ID="txtIdentity" runat="server"></asp:TextBox>        <asp:RequiredFieldValidator ID="rfvIdentity" runat="server" ControlToValidate="txtIdentity" ErrorMessage="请输入身份证号!" SetFocusOnError="True"></asp:RequiredFieldValidator>        <asp:CustomValidator ID="cvIdentity" runat="server" ControlToValidate="txtIdentity" ErrorMessage="身份证号错误!" OnServerValidate="cvInput_ServerValidate" SetFocusOnError="True"></asp:CustomValidator>        <br />        <asp:Button ID="btnSubmit" runat="server" Text="确定" Font-Size="Large" OnClick="btnSubmit_Click" />            <asp:Label ID="lblMsg" runat="server"></asp:Label>            <asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" ShowSummary="False" />        </div>    </form></body></html>
.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class MultiValidate : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void cvInput_ServerValidate(object source, ServerValidateEventArgs args)    {        //获取输入的身份证号码        string cid = args.Value;        //初始设置        args.IsValid = true;        try        {            //获取身份证号码中的出生日期并转换为DateTime类型            DateTime.Parse(cid.Substring(6, 4) + "-" + cid.Substring(10, 2) + "-" + cid.Substring(12, 2));        }        catch (Exception)        {            args.IsValid = false;        }    }    protected void btnSubmit_Click(object sender, EventArgs e)    {        lblMsg.Text = "";        if (Page.IsValid)        {            lblMsg.Text = "验证通过!";        }    }}


6.HTTP请求,响应及状态管理


HTTP请求

Page类的属性Request是一个HttpRequest对象,它封装了HTTP请求的信息。

HttpRequest对象的数据集合对应表

数据集合说明QueryString从查询字符串中读取用户提交的数据Cookies获取客户端Cookies信息ServerVariables获取服务器端和客户端环境变量信息ClientCertificate获得客户端的身份证验证信息Browser获得客户端浏览器信息
QueryString数据集合

QueryString获得的查询字符串是指跟在URL后面的变量及值,以"?"于URL间隔,不同的变量之间以"&"间隔。


ServerVariables数据集合

此数据集合可以获取服务器端或客户端的环境变量信息

语法格式如下:

Request.ServerVariables["环境变量名"]
常用的环境变量表
环境变量名说明CONTENT_LENGTH发送到客户端的文件长度CONTENT_TYPE发送到客户端的文件类型LOCAL_ADDR服务器端IP地址REMOTE_ADDR客户端IP地址REMOTE_HOST客户端计算机名SERVER_NAME服务器端计算机名SERVER_PORT服务器端网站端口号
Browser数据集合
此数据集合用来判断用户浏览器的信息
浏览器特性名对应表
名称说明Browser浏览器类型Version浏览器版本号MajorVersion浏览器主板本号MinorVersion浏览器次版本号Frames逻辑值true表示支持框架功能Cookies逻辑值true表示支持CookieJavaScript逻辑值true表示支持JavaScriptActiveXControls逻辑值true表示支持ActiveXcontrol控件

实例:运行效果

.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Request.aspx.cs" Inherits="Request" %><!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="lblMsg" runat="server" Font-Size="Large"></asp:Label>        </div>    </form></body></html>

.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Request : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        lblMsg.Text = "服务器IP地址:" + Request.ServerVariables["Local_ADDR"] + "<br />";        lblMsg.Text += "客户端IP地址:" + Request.ServerVariables["Remote_ADDR"] + "<br />";        lblMsg.Text += "浏览器类型:" + Request.Browser["Browser"] + "<br />";        lblMsg.Text += "浏览器版本:" + Request.Browser["Version"] + "<br />";        lblMsg.Text += "是否支持Cookies:" + Request.Browser["Cookies"];    }}

HTTP响应

Page类的属性Response为HttpResponse对象。

HttpResponse对象的常用属性和方法

成员说明Buffer属性逻辑值,true表示先输出到缓冲区,在处理完整个响应后再将数据输出到客户端浏览器;
false表示直接将信息输出到客户端浏览器Clear()方法当属性Buffer值为true时,Response.Clear()表示清除缓冲区数据信息End()方法终止ASP.NET应用程序执行Flush()方法立即输出缓冲区中网页Redirect()方法页面重定向,可通过URL实现数据传递Write()方法在页面上输出信息AppendToLog()方法将自定义日志信息添加到IIS日志文件中

HttpServerUtility

Page类的属性Server(即HttpServerUtility对象)封装了一些服务器端的操作。

HttpServerUtility对象的常用属性和方法表

属性和方法说明ScriptTimeout属性设置脚本文件执行的最长时间。Execute()方法停止执行当前页面,转到新的页面执行,执行完后回到原页面,继续执行HtmlEncode()方法将字符串中的XHTML元素标记转换为字符实体,如将"<"转换为&ltHtmlDecode()方法和HtmlEncode()方法作用相反MapPath()方法获取网页的物理路径Transfer()方法停止当前页面执行,转到新的页面执行,执行完后不返回UrlEncode()方法将字符串中的一些字符串转换为URL编码UrlDecode()方法和UrlEncode()方法相反

Response.Redirect() , Server.Execute() , Server.Transfer()都可完成页面的重定向。区别如下

a.  Redirect()方法重定向发生在客户端,浏览器地址会发生改变;而Server.Execute() , Server.Transfer() 发生在服务器,浏览器地址栏不会变化。

b.  Execute()方法执行新网页后会回到原网页;而Redirect() , Transfer()方法执行后不会返回。

c.  Redirect()方法可以定义到同一网站或不同网站的页面;而Execuite()和Transfer()方法只能定义到同一网站的页面。

d.  Redirect()方法在不同网页之间传递数据时,状态管理采用查询字符串形式;而Execute()和Transfer()方法的状态管理方式与Button按钮的跨网页提交方式相同。

实例:运行效果


.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Server : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        //直接输出时"<hr />"浏览器解释为一条线        Response.Write("This is a dog <hr />");        //编码后"<hr />"解释为一般字符        Response.Write(Server.HtmlEncode("This is a dog<hr />") + "<br />");        //单击链接时将丢失"张"后面的信息        Response.Write("<a href=Teacher.aspx?name=张 三>Teacher.aspx</a><br />");        //编码后再单击链接时不会丢失"张"后面的信息        Response.Write("<a href=Teacher.aspx?name=" + Server.UrlEncode("张 三") + ">Teacher.aspx</a>");    }}

跨页面提交

使用Button类型控件可以实现跨浏览器网页提交。

在跨网页提交时,需要把Button类型控件的属性PostBackUrl值设置为目标网页路径。而在目标页上,需要在页面头部田间PreviousPageType指令,设置属性VirtualPath值为源网页路径。

此时,从目标网页访问源网页中的数据的方法有两种:一是利用PreviousPage.FindControl()方法访问源网页上的控件;二是现在源网页上定义公共属性,再在目标网页上利用"PreviousPage.属性名"获取源网页中的数据。

使用Server.Execute()和ServerTransfer()方法时,目标网页也是通过PreviousPage访问源网页。

在目标网页的.cs文件中判断属性PreviousPage.IsCrossPagePostBack的值,如果为true则为跨网页提交,否则为Server.Execute()或Server.Transfer()方法提交的。

实例:跨网页提交信息

运行效果:


Cross1.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cross1.aspx.cs" Inherits="Cross1" %><!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" Font-Size="Larger" Text="用户名:"></asp:Label>        <asp:TextBox ID="txtName" runat="server" Font-Size="Large"></asp:TextBox>        <br />        <asp:Label ID="Label2" runat="server" Font-Size="Larger" Text="密   码:"></asp:Label>        <asp:TextBox ID="txtPassword" runat="server" Font-Size="Larger" TextMode="Password"></asp:TextBox>        <br />        <asp:Button ID="bunSubmit" runat="server" Font-Size="Larger" PostBackUrl="~/Cross2.aspx" Text="确认" />        </div>    </form></body></html>

Cross1.aspx.cs

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Cross1 : System.Web.UI.Page{    //公共属性Name,获取用户名文本框中内容    public string Name    {        get        {            return txtName.Text;        }    }    protected void Page_Load(object sender, EventArgs e)    {    }}

Cross2.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cross2.aspx.cs" Inherits="Cross2" %><%@ PreviousPageType VirtualPath="~/Cross1.aspx" %><!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="lblMsg" runat="server" Style="font-size: large"></asp:Label>        </div>    </form></body></html>

代码<%@ PreviousPageType VirtualPath="~/Cross1.aspx" %>为手动写入的

Cross2.aspx.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Cross2 : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        //判断是否问跨网页提交        if (PreviousPage.IsCrossPagePostBack == true)        {            //通过公共属性获取值            lblMsg.Text = "用户名:" + PreviousPage.Name + "<br />";            //先通过FindControl()找到源页面中控件,再利用控件属性获取值            TextBox txtPassword = (TextBox)PreviousPage.FindControl("txtPassword");            lblMsg.Text += "密码:" + txtPassword.Text;        }    }}


状态管理

ASP.NET的状态管理分为客户端和服务器端两种。

客户端状态是将信息保存在客户端,当客户端向服务器端发送求时,状态信息会随之发送到服务器端。具体实现可选择ViewState , ControlState . HiddenField , Cookie , QueryString。其中ControlState只能用于自定义控件的状态管理。

服务器状态是指信息保存在服务器端。具体实现可选则Session状态,Application状态或数据库支持。


ViewState(视图状态)

用于维护自身Web窗体的状态。当用户请求ASP.NET网页时,ASP.NET将ViewState封装为一个或几个隐藏的表单域传递到客户端。当用户再次提交时,ViewState也将被提交到服务器端,这样就可以保持上一次的请求状态。

ViewState是系统自己生成的。如果网页上的控件很多,ViewState就会很长,影响网站的性能和用户感受。因此对于网页和控件如果没有必要维持状态,就应该禁用ViewState。如GridView类型,最好禁用ViewState。可将EnableViewState设置为false来禁用ViewState

如果要禁止这个页面的ViewState,就要使用@Page指令

<%@ Page EnableViewState="false" Language="C#" AutoEventWireup="true" CodeFile="Cross1.aspx.cs" Inherits="Cross1" %>
HiddenField控件(隐藏域)
此控件主要用于维护自身窗体的状态,它不会显示在用户的浏览器中。HiddenField控件的成员主要属性有Value和事件ValueChanged。

要触发ValueChanged事件,需将HiddenField控件的属性EnableViewState值设为false


Cookie

Cookie是保存在客户端硬盘或内存中的一小段信息。

在客户端修改,禁用或关闭Cookie而不能有效的识别用户时,只需在web.config中加上以下的语句

<sessionState cookieless="AutoDetect"></sessionState>或<sessionState cookieless="UseUri"></sessionState>
ASP.NET提供System.Web.HttpCookie类来处理Cookie , 常用的属性是Value和Expires。属性Value用于获取或设置Cookie值,Expires用于设置Cookie到期时间。

要建立Cookie需要使用Response.Cookies数据集合,如:

Response.Cookies["Name"].Value = "张三";

也可以先创建HttpCookie对象,设置其属性,然后通过Response.Cookies.Add()方法添加。如:

HttpCookie cookie = new HttpCookie("Name");        cookie.Value = "张三";        cookie.Expires = DateTime.Now.AddDays(1);        Response.Cookies.Add(cookie);

要获取Cookie值需要使用Request.Cookies数据集合,如:

string name = Request.Cookies["Name"].Value;

Cookie实例:

Cookie.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cookie.aspx.cs" Inherits="Cookie" %><!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="lblMsg" runat="server" Style="font-size:large"></asp:Label>    </div>    </form></body></html>

Cookie.aspx.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Cookie : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        if (Request.Cookies["Name"]!=null)        {            lblMsg.Text = Request.Cookies["Name"].Value + ",欢迎您回来!";        }        else        {            Response.Redirect("CookieLogin.aspx");        }    }}

CookieLogin.aspx代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookieLogin.aspx.cs" Inherits="CookieLogin" %><!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="用户名:" Style="font-size:large"></asp:Label>        <asp:TextBox ID="txtName" runat="server" Style="font-size:large"></asp:TextBox>        <br />        <asp:Label ID="Label2" runat="server" Text="密  码:"></asp:Label>        <asp:TextBox ID="txtPassword" runat="server" Style="font-size:large" TextMode="Password"></asp:TextBox>        <br />        <asp:Button ID="btnSubmit" runat="server" Text="确认" Style="font-size:large" OnClick="btnSubmit_Click"/>    </div>    </form></body></html>
CookieLogin.aspx.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class CookieLogin : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void btnSubmit_Click(object sender, EventArgs e)    {        if (txtName.Text == "ssg" && txtPassword.Text == "111")        {            HttpCookie cookie = new HttpCookie("Name");            cookie.Value = "ssg";            cookie.Expires = DateTime.Now.AddDays(1);            Response.Cookies.Add(cookie);            Response.Redirect("Cookie.aspx");        }        else        {            Response.Write("帐号或密码错误!");        }    }}


Session

Session是会话状态,Session产生在服务器端,只能为当前访问的用户信息。

Session由System.Web.HttpSessionState类实现,使用时可直接通过Page类的Session属性访问HttpSessionState类的实例。

HttpSessionState常用的属性,方法和事件表

属性,方法和事件说明Contents属性获取当前会话状态对象的引用IsCookieless属性逻辑值,确定Session ID嵌入在URL中还是存储在Cookie中,true表示存储在Cookie中IsNewSession属性逻辑值,true表示是与当前请求一起创建的Mode属性获取当前会话状态模式SessionID属性获取会话的唯一表示IDTimeout属性获取或设置会话状态持续时间,单位为分钟,默认为20分钟Abandon()方法取消当前会话Remove()方法删除会话状态集合中的项Session_Start事件用户请求网页时触发Session_End事件用户会话结束时触发只有在web.config文件中的sessionState模式设置为InProc时,才会引发Session_End事件。如果会话模式设置为StateServer或SQLServer,则不会引发该事件。

对Session状态的赋值有两种,如:

 Session["Name"] = "张三"; Session.Contents["Name"] = "张三";
注意:Session使用的名称不区分大小写,因此不能用大小写来区分不同的变量
在ASP.NET3.5中Session状态可通过web.config中的<sessionState>元素的mode属性来设置,共有五中枚举供选择Off(禁用) , InProc(进程内) , StateServer(对立的服务状态) , SQLServer , Custom(自定义数据存储)。在实际项目中,一般选择StateServer,而对于大型网站常选用SQLServer。
Session应用实例:
Session.aspx代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Session.aspx.cs" Inherits="Session" %><!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="lblMsg" runat="server" Style="font-size"></asp:Label>    </div>    </form></body></html>
Session.aspx.cs代码

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Session : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        if (Session["Name"] != null)        {            lblMsg.Text = Session["Name"] + ",欢迎你!";        }        else        {            Response.Redirect("SessionLogin.aspx");        }    }}
SessionLogin.aspx代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SessionLogin.aspx.cs" Inherits="SessionLogin" %><!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:TextBox ID="txtName" runat="server"></asp:TextBox>        <br /> 密 码:<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>        <br />        <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="确认" />        </div>    </form></body></html>
SessionLogin.aspx.cs代码
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class SessionLogin : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void btnSubmit_Click(object sender, EventArgs e)    {        if (txtName.Text == "ssg" && txtPassword.Text == "111")        {            Session["Name"] = "ssg";            Response.Redirect("Session.aspx");        }        else        {            Response.Write("帐号或密码错误!");        }    }}
Application(应用程序状态)
Application相当于公共的全局变量,作用于整个应用程序。
Application由System.Web.HttpApplicationState类来实现。存取一个Application状态的方法和Session状态类似。但Application是面对所有用户的,所以当要修改Application状态值时,首先要调用Application.Lock()方法锁定,值修改后再调用Application.UnLock()方法解锁定。如:
Application.Lock();Application["Count"] = (int)Application["Count"] + 1;Application.UnLock();
与Application相关的事件主要有Applicaton_Start , Application_End , Application_Error ,于Session类似,这些代码都存放在Global.asax文件中。
实例:统计在线人数
Global.asax代码
<%@ Application Language="C#" %><script RunAt="server">    void Application_Start(object sender,EventArgs e){        //在应用程序启动运行时运行的代码        Application["VisitNumber"]=0;    }    void Session_Start(object sneder,EventArgs e){        //在新对话启动时运行代码        if(Application["VisitNumber"]!=null){            Application.Lock();            Application["VisitNumber"]=(int)Application["VisitNumber"]+1;            Application.UnLock();        }    }    void Session_End(object sender,EventArgs e){        //在会话结束时运行的代码        if(Application["VisitNumber"]!=null){            Application.Lock();            Application["VisitNumber"]=(int)Application["VisitNumber"]-1;            Application.UnLock();        }    }</script>
Application.aspx代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Application.aspx.cs" Inherits="Application" %><!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="lblMsg" runat="server"></asp:Label>        </div>    </form></body></html>
Application.aspx.cs代码
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;public partial class Application : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        lblMsg.Text = Application["VisitNumber"].ToString();    }}


Profile

                                             
0 0
原创粉丝点击