萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 網頁間傳值完整實作:視窗開啟、QueryString、Session 三種模式

情境:父視窗開啟子視窗,關閉時回傳值

父頁面前端

<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);
}

網頁間傳值三大經典模式

1. QueryString(URL 參數)

// 來源頁
string url = "WebForm2.aspx?name=" + TextBox1.Text + "&email=" + TextBox2.Text;
Response.Redirect(url);

// 目標頁
Label1.Text = Request.QueryString["name"];
Label2.Text = Request.QueryString["email"];

優點:簡單、可書籤;缺點:長度限制、明文、不適合敏感資料。

2. Session 變數

// 來源頁
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 共享問題。

3. Cross-Page PostBack / PreviousPage

設定 PostBackUrl,目標頁透過 PreviousPage.FindControl 取值,適用於表單驗證流程。

選擇建議

模式適用情境安全性資料大小
QueryString導航、分頁、搜尋條件低< 2KB
Session多步驟精靈、購物車、使用者狀態中視記憶體而定
Cross-Page表單送出後導向結果頁中表單資料量
copyright © 萬盛學電腦網 all rights reserved