如何在ASP.NET网页间传递数据
时间:2010-11-27 来源:秩名
重点总结
目前为止在ASP.NET网页中传递数据的方式至少有5种:
1、通过查询字符串传递数据。
2、通过HTTP POST传递数据。
3、通过会话状态传递数据。
4、通过源页的公共属性传递数据。
5、通过源页中的控件值传递数据。
到底使用哪种方式来进行数据的传递,这可能受到两方面的影响:
1、页面重定向的方式。
2、源页和目标页是否位于相同的ASP.NET应用程序中。
如果源页和目标页位于不同的ASP.NET应用程序中则只能通过查询字符串和HTTP POST传递数据。
而如果源页和目标页位于相同的ASP.NET应用程序中,则可以使用五种方式中的任意一种。
一、通过查询字符串传递数据
下面的两个URL,第一个只传递了产品编号,第二个不仅传递了产品编号,同时也传递产品名称。
http://localhost/Demo/DestinationPage.aspx?ProductID=777
http://localhost/Demo/DestinationPage.aspx?ProductID=777&ProductName=Glass
在目标页中则可以通过Page.Request.QueryString 属性来获取查询字符串中传递的键值。比如下面的代码:
1 this .Response.Write( this .Request.QueryString[ "ProductID" ]);
2 this .Response.Write( "<br />" );
3 this .Response.Write( string .Format( "ProductID={0} ProductName={1}" ,
4 this .Request.QueryString[ "ProductID" ],
5 this .Request.QueryString[ "ProductName" ]));
二、通过HTTP POST传递数据
此示例代码在源页中,为用户提供了输入用户名、生日和年龄的文本框,并且将Button控件的PostBackUrl 属性设置为DestinationPage.aspx。也就是说当单击【提交到目标页】按钮后,源页窗体的数据会被传递到DestinationPage.aspx页面。
在目标页中则通过Page.Request.Form 属性来获取这些传递过来的数据。
源页的页面源码如下:
01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SourcePage.aspx.cs" Inherits="SourcePage" %>
02
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
04 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
05 < html xmlns = " http://www.w3.org/1999/xhtml " >
06 < head runat = "server" >
07 < title >源页!</ title >
08 </ head >
09 < body >
10 < form id = "form1" runat = "server" >
11 < div >
12 User Name :
13 < asp:TextBox ID = "UserNameTextBox" runat = "server" ></ asp:TextBox >
14 < br />
15 Birth Date :
16 < asp:TextBox ID = "BirthDateTextBox" runat = "server" ></ asp:TextBox >
17 < br />
18 Age :
19 < asp:TextBox ID = "AgeTextBox" runat = "server" ></ asp:TextBox >
20 < br />
21 < asp:Button ID = "SubmitButton" runat = "server" Text = "提交到目标页"
22 PostBackUrl = "~/DestinationPage.aspx" />
23 </ div >
24 </ form >
25 </ body >
26 </ html >
目标页中获取源页窗体数据的代码如下:
01 protected void Page_Load( object sender, EventArgs e)
02 {
03 StringBuilder SBuilder = new StringBuilder();
04 NameValueCollection PostedValues =
05 this .Request.Form;
06
07 for ( int Index = 0; Index < PostedValues.Count; Index++)
08 {
09 if (PostedValues.Keys[Index].Substring(0, 2) != "__" )
10 {
11 SBuilder.Append( string .Format( "{0} = {1}" ,
12 PostedValues.Keys[Index],
13 PostedValues[Index]));
14 SBuilder.Append( "<br />" );
15 }
16 }
17
18 this .Response.Write(SBuilder.ToString());
19 }
代码中的if语句主要是为了避免获取以两个下划线__开头的隐藏字段的数据,比如__VIEWSTATE、__EVENTTARGET、__EVENTARGUMENT。当然也可以去掉这个if语句,然后就能同时获取这些隐藏字段的数据了。
标签分类:
- 系统休眠文件删除后果 如何删除计算机的休眠文件 2025-04-22
- 站群服务器是什么意思 站群服务器的作用 站群服务器和普通服务器的区别 2025-04-22
- jQuery插件有何作用 jQuery插件的使用方法 2025-04-22
- jQuery插件有哪些种类 简单的jQuery插件实例 2025-04-22
-