从另一页面后面的代码访问变量

我有一个index.aspx(index.aspx.cs),它将包含使用Server.exectue(“body.aspx”)的body.aspx(body.aspx.cs);

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.asp.cs中,有一个变量text1,我想在body.aspx.cs中使用它,该怎么做?

谢谢

我认为你错误地认为ASP.NET。 我猜你是从Windows开发人员开始的。

ASP.NET Forms与Windows Forms不同。

您必须了解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

我希望这有帮助

如果将变量标记为static ,则它将不再成为页面特定实例的属性,并成为页面类型的属性。

然后,您可以从可以查看index类的任何位置将其作为index.text1访问。

但是,这意味着该值在此页面的每个实例之间共享:如果它由页面实例(或现在可以看到的任何其他类)更改,则后续页面加载将反映更改的值。

如果你不想这样 – 如果这个变量在每个页面实例之间应该是不同的 – 那么你想要的就是不可能。 ASP.NET页面除了由服务器生成之外不存在 ,因此没有页面可供您从中获取此值。

如果这个值永远不会改变,请将其标记为const ,您不必担心改变它的事情。