1

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

4

2 回答 2

7

我认为您以错误的方式思考 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。

于 2012-10-24T08:37:17.330 回答
1

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

然后,您可以index.text1从可以看到index课程的任何地方访问它。

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

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

如果此值永远不会更改,请将其标记为const,您不必担心会更改它。

于 2012-10-24T08:19:35.900 回答