无法访问其他方法中的变量

本文关键字:变量 方法 其他 访问 | 更新日期: 2023-09-27 17:50:59

我在stackoverflow上尝试了其他解决方案,但我仍然无法做到这一点。我只希望能够在这两个方法中访问customer对象,但在最后一个方法中它总是空的。我遗漏了什么?

public class Administration_CustomerDisplay : Page
{
    private Customer customer;
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        customer = new Customer();
        customer.Name = "test";
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine(customer);   //Why is this null ?
    }
}

无法访问其他方法中的变量

客户对象只在列表更改时创建…然后您的页面在拖放列表更改后呈现,客户对象消失。

如果您希望对象在单击按钮后可用,则需要在会话中持久化该对象。

与Windows应用程序不同的是,您的Page对象不会一直驻留在内存中。每次用户发出请求时,都会在服务器上创建该对象。每个事件将对应一个不同的请求,因此对应一个不同的Page对象。第二个对象不知道第一个对象及其customer字段的值。第二个对象从来没有设置它的customer字段,所以它总是空的。

如果你想要一个值在请求之间持久化,那么你必须使用会话变量

你应该像下面这样在Session中保存实例。

public partial class Administration_CustomerDisplay : System.Web.UI.Page
{
    Customer customer;
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        customer = new Customer();
        customer.Name = "test";
        HttpContext.Current.Session["customer"] = customer;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        customer = HttpContext.Current.Session["customer"];
        Console.WriteLine(customer.Name);   //Why is this null ?
    }
}

显然消费者必须是全局变量。

public class Administration_CustomerDisplay : Page
{
    private Customer customer = new Customer();
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
           customer.Name = "test";
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Console.WriteLine(customer);   //Why is this null ?
     }
}