我有以下代码:
private List<Student> students;
public List<Student> Collection()
{
students = new List<Student>
{
new Student {Id = 1, Name = "Name1"},
new Student {Id = 2, Name = "Name2"},
new Student {Id = 3, Name = "Name3"},
};
return students;
}
protected void LinkButton1_OnClick(object sender, EventArgs e)
{
var s = (sender as LinkButton).CommandArgument;
var st = students.Find(c => c.Id == int.Parse(s));
students.Remove(st);
repeater.DataBind();
}
在 LinkButton1_OnClick
事件中,students
为 null。为什么?我有similar issue在 ASP.NET MVC 中,我被告知 MVC 是无状态的,我应该使用 session
。 我的问题:ASP.NET Webforms 也是无状态的吗? 该程序通过使用 Sessions 来工作,但是如果 ASP.NET Webforms 不是无状态的,为什么我应该在这个示例中使用 Sessions?
最佳答案
整个网络都是无状态的,除非你做一些事情来添加状态。在 Web 表单中,您可以使用 ViewState或 session 。或者您可以回发列表所需的数据,或从数据库重新查询它。
请注意,不建议使用 ViewState,因为它会大大增加请求和响应的大小。
按代码方式使用 ViewState 与 Session 类似。
// add to viewstate
List<Student> students = Collection();
ViewState["students"] = students;
// later we can retrieve them
// cast is necessary because it comes back from the ViewState as an object
List<Student> students = (List<Student>)ViewState["students"];
请记住,在 Web 窗体中,每次访问页面时,都会创建页面类的一个新实例。因此字段和属性将丢失您设置的值。
关于c# - 从列表中删除项目 ASP.NET Webforms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36574379/