0

你好我正在做一个非常简单的 Asp.net 应用程序项目

 namespace WebApplication1
 {
 public partial class WebUserControl1 : System.Web.UI.UserControl
 {
    market m = new market();

    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void button_clickSell(object sender, EventArgs e) 
    {


        float price = float.Parse(this.BoxIdPrezzo.Text);

        m.insertProd("xxx", 10, "yyy");
        m.addOfferForProd("ooo", 5, "gggg");
        m.insertProd(this.BoxIdDescrizione.Text,price,this.BoxIdUtente.Text);
        String s;
        m.outMarket(out s);  
        this.Output.Text = s;  //the output here work good
        this.Output.Visible = true;

    }
    protected void button_clickView(object sender, EventArgs e) 
    {
        String s;
        m.outMarket(out s);
        this.Output.Text = s;  // here seem to have lost the reference to product why?
        this.Output.Visible = true;
    }
}
}

问题是,当我单击调用 button_clickSell 的 button1 时,一切正常,但是当我单击调用 button_clickView 的 button2 时,产品似乎不再出现在 Market 对象中,但这很奇怪,因为在市场对象中我有一个产品列表和 m.outMarket 在第一时间正常工作。

4

3 回答 3

4

那是因为页面的工作方式。每次您向页面发出请求或回发时,该变量中的值都会丢失。

你需要在一个会话或类似的东西中保持它。

这是使用会话的一个非常基本的示例。

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Collection"] == null)
        {
            Session["Collection"] = new List<int>();
        }//if
    }
    protected void button_clickSell(object sender, EventArgs e)
    {
        List<int> collection = (List<int>)Session["Collection"];
        collection.Add(7);
        collection.Add(9);
    }
    protected void button_clickView(object sender, EventArgs e)
    {
        List<int> collection = (List<int>)Session["Collection"];
        collection.Add(10);
    }
于 2012-04-01T07:28:50.960 回答
0

你可以在 MSDN 上查看这篇文章:ASP.NET Session State Overview

于 2012-04-01T07:45:01.963 回答
0

Session当需要跨页面的信息时应使用。现在是位于同一页面上的两个按钮的问题。所以 ViewState 是最好的选择。

protected void Page_Load(object sender, EventArgs e)
{
     if (ViewState["Collection"] == null)
     {
            ViewState["Collection"] = new List<int>();
     }//if
}
protected void button_clickSell(object sender, EventArgs e)
{
     List<int> collection = (List<int>)ViewState["Collection"];
     collection.Add(7);
     collection.Add(9);
}
protected void button_clickView(object sender, EventArgs e)
{
     List<int> collection = (List<int>)ViewState["Collection"];
     collection.Add(10);
}
于 2012-04-01T08:41:11.760 回答