2014/09/18

ASP.Net 不同頁面透過Session互相傳遞資料


A Layout:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebFormDemo.aspx.cs" Inherits="Demo.WebFormDemo" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="buttonSend" runat="server" OnClick="buttonSend_Click" Text="Button" />
    </div>
    </form>
</body>
</html>


B Layout:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebFormDemo2.aspx.cs" Inherits="Demo.WebFormDemo2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox" runat="server" Height="300px" Width="400px" TextMode="MultiLine"></asp:TextBox>
    </div>
    </form>
</body>
</html>




A Code:

using System;

namespace Demo
{
    public partial class WebFormDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void buttonSend_Click(object sender, EventArgs e)
        {
            for (int index = 1; index <= 10; index++)
                Session.Add(index.ToString(), index.ToString());
            Server.Transfer("~\\WebFormDemo2.aspx");
        }

    }
}


B Code:

using System;
using System.Web.UI.WebControls;

namespace Demo
{
    public partial class WebFormDemo2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                string str = string.Empty;

                foreach (string key in Session.Keys)
                    str += Session[key] + "<br/>";

                TextBox.Text = str.Replace("<br/>", Environment.NewLine);
        }
    }
}


A頁面先將要傳送的資料放入Session,並點擊按鈕,使用Server.Transfer方法切換頁面以及資料傳給B頁面


B頁面在Page Load狀況會去讀取資料並設定到TextBox文字方塊內

執行成果:








參考資料:
http://msdn.microsoft.com/zh-tw/library/6c3yckfw(v=vs.100).aspx
http://forums.asp.net/t/1173162.aspx?Go+to+url+when+button+pressed
http://www.dotblogs.com.tw/jimmyyu/archive/2009/11/10/11503.aspx