之前写了一篇文章介绍Server.Transer()方法的使用及HttpContext类 , 这两天试验了使用Context.Items字典与Session对象在页面间传递值,或者保存持久数据,觉得有必要整理一下各自的特点.
Context字典与Session都可以保存任意的object,不同的是Context字典中的对象只在某个Http Request中有效,到了下一个Request的时候就无效了, 因此要使用Context字典传值,需要用Server.Transer()方法跳转到新页面, 新页面首次加载(!IsPostBack)时读取Context字典中的对象,在以后回发时, 因为Http Request不是来自先前的页面,而是来自新页面的请求, 因此并不能读取到Former Page中的Context字典数据.
FormerPage.aspx (类名FormerPage, ds是FormerPage类中的一个DataSet字段):
private
void
btnToNewPage_Click(
object
sender, System.EventArgs e)

{
Context.Items["string"] = "I am a string";//可用Context字典来存储信息, Transfer到新的页面后,首次加载新页面时,可以获取Context字典信息.
Context.Items["contextData"] = ds;// Context 可保存任意数据类型,Context字典特定于某个Http请求,对于不同客户端,值不一样

Application["appData"] = ds;//Application可保存任何数据类型,对所有客户端有同样值,整个应用程序范围内有效

Session["sessionData"] = ds;// Session可以保存任意的object类型,对不同客户端不同值

HttpCookie cookie = new HttpCookie("string","I am a string"); //cookie存储在客户端,只能保存字符串,对不同客户端有不同值
Response.Cookies.Add(cookie);

Server.Transfer("NewPage.aspx",false);
}
上面的代码中页使用了Application和Cookie来保存页面持久数据,其特点在注释中已经注明. Application,Session,Cookie对象,可以在跟踪页面时查看集合中的数据或者数据名及类型.
方法是在Page_Load时设置Trace.IsEnabled = true;或者aspx页首行代码中指定:
<%@ Page language="c#" Trace="true" Codebehind="WebGridTest.aspx.cs" Inherits="WebGridTest" %>
NewPage.aspx中调用Context字典:
private
void
Page_Load(
object
sender, System.EventArgs e)

{
// Page Load at the first time:
if(!IsPostBack)

{
try

{
FormerPage formerPage = (FormerPage)Context.Handler; // Get Former Request Page
DataSet ds = formerPage.GetDataSet(); // Invoke method of the Former Request Page
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
catch

{
Response.Write("Error get data from parent transfer page!");
}
}

// Page Load of each time:
try

{
DataSet dat = null;
string str = string.Empty;

if (Context.Items["string"]!=null) //Get the "string" item in the Context Dictionary
str = (string)Context.Items["string"];
if(Context.Items["contextData"]!=null) //Get the "contextData" item in the Context Dictionary, it is a DataSet object
dat = Context.Items["contextData"] as DataSet;

if(str!=null&&str!=string.Empty)

{
//output the string:
Response.Write("<script>alert('string gotted:" + str + "');</script>");
}
if(dat!=null)

{
//output the rows count of dataset
Response.Write("<script>alert('DataSet Rows Count:" + dat.Tables[0].Rows.Count + "');</script>");
}
}
catch(Exception _ex)

{
Response.Write("<script>alert('Exception caught:" + _ex.Message + "');</script>");
}

string path = Context.Request.Path; //Get the request file path
Response.Write("<script>alert('Request From:" + path + "');</script>");
}
当点击FormerPage.aspx 的ToNewPage按钮时,跳转到NewPage.aspx, 此时浏览器显示的URL仍然是FormerPage.aspx, NewPage加载时会显示读取到的Context字典中的字符串值和dataset的记录数;
之后从新的浏览器窗口再次打开NewPage.aspx, 或者再NewPage页面点其他按钮,引起回发后, NewPage加载时并不能读取到FormerPage中定义的Context字典的数据,因为此时的请求来自NewPage,而非FormerPage
Reference: