![](/img/trans.png)
[英]How do I access properties from global.asax in some other page's code behind
[英]How do I access a variable from the code behind of another page?
我有一個 index.aspx (index.aspx.cs) 它將包含 body.aspx (body.aspx.cs) 使用Server.execute("body.aspx");
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
public partial class index : System.Web.UI.Page
{
public string text1 = "abc";
protected void Page_Load(object sender, EventArgs e)
{
}
}
在 index.aspx.cs 中,我想在 body.aspx.cs 中使用一個變量text1
,該怎么做?
我認為您對 ASP.NET 的看法是錯誤的。 我猜你是從 Windows 開發人員開始的。
ASP.NET 窗體與 Windows 窗體不同。
您必須了解 ASP.NET 頁面只存在於請求被提供之前。 然后它“死了”。
您不能像使用 Windows 窗體那樣從/向頁面傳遞變量。
如果您想從另一個頁面訪問內容。 然后這個頁面必須將這條信息存儲在一個 SESSION 對象中,然后你從另一個頁面訪問那個會話對象並獲得你想要的值。
讓我給你舉個例子:
第 1 頁:
public string text1 = "abc";
protected void Page_Load(object sender, EventArgs e)
{
Session["FirstName"] = text1;
}
第2頁:
protected void Page_Load(object sender, EventArgs e)
{
string text1;
text1 = Session["FirstName"].ToString();
}
這就是您在未鏈接在一起的頁面之間傳遞值的方式。
此外,您可以通過修改查詢字符串來傳遞值(向 URL 添加變量)。
例子:
第1頁:(按鈕點擊事件)
private void btnSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
}
第2頁:
private void Page_Load(object sender, System.EventArgs e)
{
this.txtBox1.Text = Request.QueryString["Name"];
this.txtBox2.Text = Request.QueryString["LastName"];
}
這就是你應該如何在頁面之間傳遞變量
此外,如果您希望在您網站的所有訪問者之間共享一個值。 那么你應該考慮使用 Application 而不是 Session。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.