<script type="text/javascript">
function OpenSubForm(ret) {
var strPath = "SubForm.aspx";
var nHeight = 500, nWidth = 500;
var feature = "Height=" + nHeight + ",Width=" + nWidth + ",top=30,left=30";
feature += ",dependent=yes,location=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no";
window.open(strPath + "?Ret_Form=Form1&Ret_Value=" + ret, 'subForm', feature).focus();
return false;
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onClick", "return OpenSubForm('TextBox1');");
}
protected void Button1_Click(object sender, EventArgs e)
{
string retForm = Request.Params["Ret_Form"] ?? "document.forms[0]";
string retValue = Request.Params["Ret_Value"];
string script = $@"
<script language=javascript>
window.opener.{retForm}.{retValue}.value='{TextBox1.Text.Trim()}';
window.close();
</script>";
Response.Write(script);
}
// 來源頁
string url = "WebForm2.aspx?name=" + TextBox1.Text + "&email=" + TextBox2.Text;
Response.Redirect(url);
// 目標頁
Label1.Text = Request.QueryString["name"];
Label2.Text = Request.QueryString["email"];
優點:簡單、可書籤;缺點:長度限制、明文、不適合敏感資料。
// 來源頁
Session["name"] = TextBox1.Text;
Session["email"] = TextBox2.Text;
Server.Transfer("WebForm2.aspx");
// 目標頁
Label1.Text = Session["name"].ToString();
Label2.Text = Session["email"].ToString();
Session.Remove("name");
Session.Remove("email");
優點:資料不曝光、容量大;缺點:伺服器記憶體佔用、需注意 Session 逾時與 Web Farm 共享問題。
設定 PostBackUrl,目標頁透過 PreviousPage.FindControl 取值,適用於表單驗證流程。
| 模式 | 適用情境 | 安全性 | 資料大小 |
|---|---|---|---|
| QueryString | 導航、分頁、搜尋條件 | 低 | < 2KB |
| Session | 多步驟精靈、購物車、使用者狀態 | 中 | 視記憶體而定 |
| Cross-Page | 表單送出後導向結果頁 | 中 | 表單資料量 |