我想将List<StockInList>
绑定到GridView
,向用户展示,然后让他们回来(也许用户会编辑它们)来做其他事情。但是,当我检索绑定项stockInLists
时,它是null
。原因我猜是ASP创建了一个新的Code-Behind类Add_Inventories
来处理请求,所以我失去了对绑定项stockInLists
的访问权。
我做错了吗?我该怎么做才能正确地恢复它们?
public partial class Add_Inventories : System.Web.UI.Page
{
private ShoppingDbContext shoppingDbContext = new ShoppingDbContext();
private List<StockInList> stockInLists;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var stockInListsFromSession =(List<StockInList>)Session["stock_in_list"];
if (stockInListsFromSession != null)
{
//save the stockInLists in private filed, so that I can get them back, however it's null when method `Add()` invoke.
stockInLists=new List<StockInList>(stockInListsFromSession);
GridView1.DataSource = stockInLists;
GridView1.DataBind();
}
else
{
//...
}
}
}
protected async void Add(object sender, EventArgs e)
{
foreach (var stockInList in stockInLists)
{
shoppingDbContext.StockInLists.Add(stockInList);
}
await shoppingDbContext.SaveChangesAsync();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
答案 0 :(得分:0)
刷新页面时,变量中的数据会丢失(范围),为了防止它,我们应该使用Sessions,viewstate等或将该变量设置为静态(不推荐)。
在您的情况下,如果刷新页面, stockInLists 中存储的值将会丢失,
ViewState["stockInLists"] = stockInLists;
Session("stockInLists") = stockInLists;
(推荐)private List<StockInList> stockInLists;
(不推荐)我希望你理解它:)