方法1:使用状态试图:ViewState,
有效期等于页面的生命周期,仅服务器控件可用(runat=”server”)。
ViewState是用于在页面提交自身的情况下保存页面数据状态的一个对象。
本质:页面上的一个叫做__ViewState的<input type=“hidden”的隐藏域标签。
语法:
ViewState["nameid"] = TextBox1.Text;//存储信息 TextBox2.Text= ViewState["nameid"].ToString();//读取信息 |
使用例子:
protected void Button1_Click(object sender, EventArgs e) { ViewState["textbox"] = TextBox1.Text; } protected void Button2_Click(object sender, EventArgs e) { TextBox2.Text= ViewState["textbox"].ToString(); } |
在page指令中加入EnableViewState="false",可禁止整个页面的ViewState
使用注意:
ViewState虽然使用方便,但是谨慎使用,因为使用过多,会大幅度降低应用程序的性能(速度)。
方法2:使用隐藏控件传值
<input type="text" id="text1" runat="server" visible="false" /> |
页数数据传递
IsPostBack介绍
IsPostBack是Page类有一个bool类型的属性,用来判断针对当前Form的请求是第一次还是非第一次请求。当IsPostBack=true时表示非第一次
点击按钮就不是第2次访问了
protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { Response.Write("<script>alert('我不是第一次访问!')</script>"); } else { Response.Write("<script>alert('我是第Ì一次访问!')</script>"); } } |
面传值的实现原理图
跨页面传值例子:
页面a.aspx
<table border="1" style="width: 58%;"> <tr> <td class="style1">请输入您的姓名</td> <td><asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td> </tr> <tr> <td class="style1"><asp:Button ID="Button1" runat="server" Text="提交本页面" onclick="Button1_Click" /></td> <td><asp:Button ID="Button2" runat="server" Text="提交到b.aspx" PostBackUrl="b.aspx" /></td> </tr> <tr> <td class="style1"><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></td> <td></td> </tr> </table> |
a.aspx.cs文件
protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "hello" + TextBox1.Text; } |
页面b.aspx
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> |
b.aspx.cs代码
protected void Page_Load(object sender, EventArgs e) { if(Page.PreviousPage!=null) { TextBox t1 = (TextBox)PreviousPage.FindControl("TextBox1"); if (t1 != null) { Label1.Text = "hello" + t1.Text; } } } |