目标页中获取源页窗体数据的代码如下:
protected void Page_Load(object sender, EventArgs e) { StringBuilder SBuilder = new StringBuilder(); NameValueCollection PostedValues = this.Request.Form; for (int Index = 0; Index < PostedValues.Count; Index++) { if (PostedValues.Keys[Index].Substring(0, 2) != "__") { SBuilder.Append(string.Format("{0} = {1}", PostedValues.Keys[Index], PostedValues[Index])); SBuilder.Append("<br />"); } } this.Response.Write(SBuilder.ToString()); } |
代码中的if语句主要是为了避免获取以两个下划线__开头的隐藏字段的数据,比如__VIEWSTATE、__EVENTTARGET、__EVENTARGUMENT。当然也可以去掉这个if语句,然后就能同时获取这些隐藏字段的数据了。
三、通过会话状态传递数据
使用会话状态的好处是可以在与源页处于相同ASP.NET应用程序的所有网页间共享数据。缺点是会增加服务器的内存开销。
下面的代码中,用户在源页的【用户名】文本框中输入自己的姓名,然后单击【提交数据】按钮。服务器代码会通过Page.Session属性将用户名存储到会话状态中,然后使用Response.Redirect()方法将页面强制重定向到另外一个页面(DestinationPage.aspx)。在这个目标页面中再次通过Page.Session属性来获取用户在源页中保存的用户名。
源页的源代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SourcePage.aspx.cs" Inherits="SourcePage" %> <!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:TextBox ID="UserNameTextBox" runat="server"></asp:TextBox> <asp:Button ID="SubmitButton" runat="server" Text="提交数据" onclick="SubmitButton_Click" /> </div> </form> </body> </html> |
源页中用来保存用户名到会话状态并重定向到目标页的代码如下:
protected void SubmitButton_Click(object sender, EventArgs e) { this.Session["UserName"] = this.UserNameTextBox.Text; this.Response.Redirect("DestinationPage.aspx"); } |
目标页中获取保存在会话状态中的用户名的代码如下:
protected void Page_Load(object sender, EventArgs e) { string UserName = this.Session["UserName"].ToString(); this.Response.Write(UserName); } |