ASP.NET Web Forms 頁面間傳遞資料有多種方式,各有適用場景與優缺點。本文系統比較 **Cross-Page Postback (PreviousPage)**、`QueryString`、`Session`、`Context.Items`、`Server.Transfer`、`Cookie`、`ViewState` 跨頁面等 7 大方法,附程式碼範例與選擇指南。
| 方法 | 資料型別 | 生命週期 | 可見性 | 適用場景 | 缺點 |
|---|---|---|---|---|---|
| PreviousPage (Cross-Page Postback) | 控制項值 | 單次請求 | URL 不變 | 表單提交到另一頁、Wizard 步驟 | 緊耦合來源頁面控制項 ID、需 Postback |
| QueryString | 字串 | 單次請求 | URL 可見 | 簡單參數傳遞、書籤分享、SEO | 長度限制、不安全、不可傳複雜物件 |
| Session | 任意物件 | 跨請求 (逾時前) | 伺服器端 | 購物車、多步驟精靈、使用者狀態 | 記憶體壓力、需序列化、Web Farm 需共享 Session |
| Context.Items | 任意物件 | 單次請求 (含 Transfer) | 伺服器端 | `Server.Transfer` 內部傳遞大量資料 | Redirect 失效、僅限同一請求管線 |
| Server.Transfer | 整個頁面上下文 | 單次請求 | URL 不變 | 內部頁面跳轉、保留表單資料 | 瀏覽器網址列不同步、書籤失效 |
| Cookie | 字串 | 持久化 (設定過期) | 客戶端可見 | 記住我、偏好設定、追蹤 | 大小限制 4KB、可被竄改/停用 |
| Cache/Application | 任意物件 | 全域/依策略 | 伺服器端 | 共用資料、快取 | 非用戶專屬、需鎖定同步 |
來源頁面 (Source.aspx) 按鈕設定 `PostBackUrl="~/Target.aspx"`:
目標頁面 (Target.aspx) 使用 `PreviousPage` 強型別存取:
public partial class Target : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack && PreviousPage != null)
{
// 強型別轉型 (需在 Source.aspx 加入 <%@ PreviousPageType VirtualPath="~/Source.aspx" %>)
var source = PreviousPage as Source;
if (source != null)
{
lblResult.Text = $"姓名: {source.txtName.Text}, 日期: {source.calDate.SelectedDate:d}";
}
else
{
// 弱型別 FindControl (不需 PreviousPageType)
var txt = PreviousPage.FindControl("txtName") as TextBox;
var cal = PreviousPage.FindControl("calDate") as Calendar;
lblResult.Text = $"姓名: {txt?.Text}, 日期: {cal?.SelectedDate:d}";
}
}
}
}
**關鍵**:來源頁面加入 `<%@ PreviousPageType VirtualPath="~/Source.aspx" %>` 即可獲得強型別 `PreviousPage`,享受 IntelliSense 與編譯時期檢查。
// 來源頁
Response.Redirect($"Target.aspx?name={Server.UrlEncode(txtName.Text)}&date={calDate.SelectedDate:yyyy-MM-dd}");
// 目標頁
string name = Request.QueryString["name"];
DateTime date = DateTime.Parse(Request.QueryString["date"]);
優點:可書籤、可分享、支援 GET、無伺服器狀態。缺點:敏感資料不可用、長度 ~2KB。
// 來源頁
Session["WizardData"] = new WizardModel { Name = txtName.Text, Date = calDate.SelectedDate };
Response.Redirect("Target.aspx");
// 目標頁
var model = Session["WizardData"] as WizardModel;
if (model != null) { ... }
Session.Remove("WizardData"); // 用完即刪
// 來源頁
Context.Items["BigData"] = hugeDataTable;
Server.Transfer("Target.aspx"); // URL 不變,同一請求管線
// 目標頁
var data = Context.Items["BigData"] as DataTable;
優點:避免序列化、大物件高效傳遞、URL 不變。缺點:Redirect 失效、瀏覽器網址列不同步。
| Web Forms | MVC / Core |
|---|---|
| PostBackUrl / PreviousPage | Controller Action 參數繫結、TempData (Redirect 後保留一請求) |
| Session | Session / IDistributedCache (Redis) |
| QueryString | Route Data / Query String / Model Binding |
| Context.Items | `HttpContext.Items` (Middleware 間傳遞) |
| Server.Transfer | 不存在,改用內部服務呼叫或重新設計流程 |
理解各種傳值機制的生命週期、可見度、耦合度,能根據業務需求選擇最適合的方案,避免濫用 Session 導致擴展性問題。