ASP.NET页面间跳转和传递数据(转)

在ASP.NET中,从一个页面到另一个页面,如何实现跨页数据传递呢?
    例如源页面Default.aspx有一个文本框(txtMsg)和一个按钮(btnOK),要求单击按钮时跳转到目标页面Target.aspx,并在目标页面显示txtMsg的文本。
    主要有以下几种方法:

 1. 设置Default.aspx的按钮btnOK的PostBackUrl属性为目标页;
    Target.aspx添加代码:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null)
        {
            if (PreviousPage.IsCrossPagePostBack)
            {
                string msg = ((TextBox)PreviousPage.FindControl("txtMsg")).Text;
                Response.Write("这是跨页回发,传递的信息是:" + msg);
            }
        }
    }

  2. 使用Session
     Default.aspx:
         protected void btnOK_Click(object sender, EventArgs e)
         {
            Session["msg"] = txtMsg.Text.Trim();
            Response.Redirect("Target.aspx");
         }
     Target.aspx:
         protected void Page_Load(object sender, EventArgs e)
         {
            if(Session["msg"]!=null)
                Response.Write("这是Session传值,传递的信息是:" + Session["msg"].ToString());
         }

  3. 使用Cookie
     Default.aspx:
         protected void btnOK_Click(object sender, EventArgs e)
         {
            Response.Cookies["msg"].Value = txtMsg.Text.Trim();
            Response.Redirect("Target.aspx");
         }
     Target.aspx:
         protected void Page_Load(object sender, EventArgs e)
         {
            if(Request.Cookies["msg"]!=null)
                Response.Write("这是Cookie传值,传递的信息是:" + Request.Cookies["msg"].Value);
         }

  4. 使用QueryString
     Default.aspx:
         protected void btnOK_Click(object sender, EventArgs e)
         {
            Response.Redirect("Target.aspx?msg="+txtMsg.Text.Trim());
         }
     Target.aspx:
         protected void Page_Load(object sender, EventArgs e)
         {
            if(Request.QueryString["msg"]!=null)
                Response.Write("这是QueryString传值,传递的信息是:" + Request.QueryString["msg"].ToString());
         }

  5. 使用Transfer
     Default.aspx:
         protected void btnOK_Click(object sender, EventArgs e)
         {
            Server.Transfer("Target.aspx");
         }
         public string Msg
         {
            get {   return txtMsg.Text.Trim(); }
         }
     Target.aspx:
         protected void Page_Load(object sender, EventArgs e)
         {
            if (PreviousPage != null)
            {
                _Default f1 = (_Default)Context.Handler;
                if (f1 != null)
                    Response.Write("这是Transfer传值,传递的信息是:" + f1.Msg);
            }
         }

 原文地址 : http://blog.sina.com.cn/s/blog_5fbcb5610100oz9x.html

posted @ 2012-02-29 15:26  Chendisheng  阅读(437)  评论(0编辑  收藏  举报