<%@ Page Language="C#" %> <%@ PreviousPageType VirtualPath="~/FirstPage.aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { this.Label1.Text = "Your Name is : " + PreviousPage.UserName; } </script>
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Second Page</title> </head> <body> <form id="form1" runat="server"> <div> <h1>This is the Second Page</h1> <p><asp:Label ID="Label1" runat="server"></asp:Label> </p> </div> </form> </body> </html>
打开FirstPage.aspx,输入内容并按下"Postback to Second Page"按钮提交,页面就会提交到SecondPage.aspx,输入的内容也会显示在SecondPage.aspx上。注意FirstPage.aspx中Button2新增的PostBackUrl属性,还有SecondPage.aspx中的@PreviousPageType指令。这些新增的内容,正是ASP.NET 2.0 中的跨页提交的方案的组成部分。
ASP.NET 2.0中,Button控件有个新增的属性PostBackUrl,用来设置需要提交的目标页面。因为只要指定Button控件的PostBackUrl属性就可以提交到其它页面,我们可以在页面中使用多个控件配置其PostBackUrl的属性,提交到不同的页面。当然也可配置多个页面提交到同一个页面。
ASP.NET 2.0的Page类新增了一个PreviousPage属性。顾名思义,目标页面中的这个属性包含对源页面的引用。这样就可以在目标页面中通过PreviousPage属性访问源页面的信息,我们一般使用FindControl方法来查找源页面上的控件并读取这些控件的值。下面的代码说明了该方法的使用:
if (Page.PreviousPage != null) { TextBox txtName = (TextBox)Page.PreviousPage.FindControl("txtName"); if (txtName != null) { Label1.Text = txtName.Text; } }