如何从另一个页面后面的代码访问变量? [英] How do I access a variable from the code behind of another page?

查看:54
本文介绍了如何从另一个页面后面的代码访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个index.aspx(index.aspx.cs),其中将使用 Server.execute("body.aspx");包括body.aspx(body.aspx.cs);

I have an index.aspx (index.aspx.cs) which will include the body.aspx (body.aspx.cs) using 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 ,该怎么做?

In index.aspx.cs, there is a variable text1 which I want to use in body.aspx.cs, how to do that?

推荐答案

我认为您在以错误的方式考虑ASP.NET.我猜你是从Windows Developer开始的.

I think you're thinking of ASP.NET the wrong way. I guess you started as a Windows Developer.

ASP.NET表单与Windows表单不同.

ASP.NET Forms are not like Windows Forms.

您必须了解,ASP.NET页仅在提供请求之前有效.然后它死亡".

You have to understand that the ASP.NET page only lives until the request is being served. And then it "dies".

您不能像使用Windows Forms一样在页面之间传递变量.

You cannot pass variables from/to pages the same way you do with Windows Forms.

如果要从另一个页面访问内容.然后,此页面必须将该信息存储在SESSION对象中,然后您可以从其他页面访问该会话对象并获取所需的值.

If you want to access contents from another page. Then this page MUST store that piece of information inside a SESSION object and then you access that session object from a different page and get the value that you want.

让我给你举个例子:

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

这就是您如何在未链接在一起的页面之间传递值.

That's how you pass values between pages that are not linked together.

此外,您还可以通过修改查询字符串(将变量添加到URL)来使用传递值.

Also, you can pass values using by modifying the Query string (add variables to the URL).

示例:

第1页:(按钮单击事件)

Page 1: (button click event)

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"];
}

这是您应该在页面之间传递变量的方式

this is how you should pass variables between pages

此外,如果您希望在网站的所有访问者之间共享一个值.然后,您应该考虑使用应用程序而不是会话.

Also, if you want a value to be shared between ALL visitors of your website. Then you should consider using Application instead of Session.

这篇关于如何从另一个页面后面的代码访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆