在页面之间传递对象

时间:2014-09-01 15:41:22

标签: c# asp.net

我遇到了一些问题,需要一些帮助

我想要做的是从一个页面传递一个对象并将其传递给另一个页面。

这对C#来说没问题,因为代码看起来像。

namespace WindowsFormsApplication1
{
public class Class1
{
    private String firstName;
    private String surName;
    private int age;

    public Class1()
    {

    }

    public String FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }

    public String SurName
    {
        get { return surName; }
        set { surName = value; }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }
}

表格看起来像

private void button1_Click(object sender, EventArgs e)
    {
        Class1 class1 = new Class1();
        class1.FirstName = textBoxFirstname.Text;
        class1.SurName = textBoxSurname.Text;
        class1.Age =  int.Parse(textBoxAge.Text);

        Form2 form2 = new Form2(class1);
        form2.Show();
    }

public partial class Form2 : Form
{
    private Class1 class1;

    public Form2(Class1 class1)
    {
        InitializeComponent();
        this.class1 = class1;

        label2.Text = (class1.FirstName + " " + class1.SurName);
        label4.Text = Convert.ToString(class1.Age);
    }
}

这是我到目前为止所提出的

这些是页面

    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        Class1 class1 = new Class1();
        class1.FirstName = TextBoxFirstName.Text;
        class1.SurName = TextBoxSurname.Text;
        class1.Age = int.Parse(TextBoxAge.Text);

        //Missing code
    }
    }

这是第二种形式

<body>
<form id="form1" runat="server">
<div>

    <asp:Label ID="Label1" runat="server" Text="Details"></asp:Label><br />
    <asp:Label ID="Label2" runat="server" Text="Name"></asp:Label>
    <asp:Label ID="Label3" runat="server" Text="Name"></asp:Label>

    <br />

    <asp:Label ID="Label4" runat="server" Text="Name"></asp:Label>
    <asp:Label ID="Label5" runat="server" Text="Label"></asp:Label>
    <br />

</div>
</form>
</body>

这是后面的代码

public partial class WebForm2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //missing code to display label 3

        //Missing code to display label 5
    }
}

2 个答案:

答案 0 :(得分:0)

使用Sessions

在会话中保存您需要的信息(例如Class1的实例),并在其他页面中重复使用它:

Button_Click的Page1上:

Session["YourSessionName"] = class1Instance;

Page_Load的第2页上:

if (Session["YourSessionName"] != null) //Check if session is empty
{
    Class1 class1InstanceOnPage2 = (Class1)Session["YourSessionName"];
}

然后你可以重复使用课堂上的所有东西。 这也适用于字符串等。

但这仅适用于ASP.NET而不适用于WinForms。

我不明白为什么要混淆它,这是不可能的。

答案 1 :(得分:0)

在ASP.Net中,您不会将对象直接传递到其他页面。在某种意义上,页面与每个页面断开连接,但仅通过用户输入连接。

要传递数据而不是对象(这是正确的思考方式),您可以通过查询字符串传递它,如果它不是私有的,并且您不担心通过Session对象进行篡改,如果它需要是私有的,或者通过存储它的数据库,然后在另一个页面中检索。

网络与原生应用不同!

相关问题