[英]ASP Web Forms: Where should I put the bound item?
I'd like to bind a List<StockInList>
to a GridView
, show them to user, and get them back(perhaps user will edit them) to do something else. 我想将
List<StockInList>
绑定到GridView
,将其显示给用户,然后取回它们(也许用户会对其进行编辑)以执行其他操作。 However, when I retrieved the bound item stockInLists
, it's null
. 但是,当我检索绑定项目
stockInLists
,它为null
。 Reason I guess is that ASP create a new Code-Behind class Add_Inventories
to handle request, so I lost the access to my bound item stockInLists
. 我猜想原因是ASP创建了一个新的Code-Behind类
Add_Inventories
来处理请求,因此我失去了对绑定项stockInLists
的访问权限。
Am I doing something wrong? 难道我做错了什么? What should I do to get them back correctly?
我应该怎么做才能正确地把它们找回来?
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);
}
}
The data in variables are lost when page is refreshed(Scope), to prevent it we should use Sessions, viewstate etc or make that variable as static(Not recommended). 刷新页面时变量中的数据会丢失(范围),为防止这种情况,我们应使用Sessions,viewstate等或将变量设置为静态(不推荐)。
In your case value stored in stockInLists will be lost if the page is refreshed, 如果您刷新页面,则存储在stockInLists中的值将丢失,
ViewState["stockInLists"] = stockInLists;
ViewState["stockInLists"] = stockInLists;
Session("stockInLists") = stockInLists;
Session("stockInLists") = stockInLists;
(Recommended) private List<StockInList> stockInLists;
private List<StockInList> stockInLists;
(Not Recommended) I hope you understand it :) 我希望你能理解:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.