C# asp.net 对象引用丢失
本文关键字:对象引用 net asp | 更新日期: 2023-09-27 18:29:43
你好,我正在做一个非常简单的 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的按钮 1 时,一切正常,但是当我单击调用button_clickView产品的按钮 2 时,产品似乎不再出现在市场对象中,但这很奇怪,因为在市场对象中我有一个产品和 m.outMarket 列表在第一次正确工作。
这是因为页面的工作方式。每次向页面发出请求或回发时,该变量中的值都将丢失。
您需要在会话或类似内容中保留它。
下面是使用会话的一个非常基本的示例。
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);
}
您可以在
MSDN上查看此文章: ASP.NET 会话状态概述
当需要跨
Session
.pages。现在两个按钮躺在同一页上的问题。所以 视图状态是最佳选择。
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);
}