从列表ASP.NET MVC中删除项目

我有一份Student名单。 每次我点击删除链接时,它会从列表中删除所选的学生,但如果我重复单击另一条记录的删除链接,我的列表将返回默认初始化,然后删除新记录。 我知道我的问题是因为我在控制器的构造函数中初始化了我的列表。 那么我应该在哪里初始化我的列表,而不是在回发中重新初始化?

 List lst; public HomeController() { lst = new List { new Student {Id = 1, Name = "Name1"}, new Student{Id = 2 , Name = "Name2"}, new Student{Id = 3 , Name = "Name3"}, }; } public ActionResult Index() { return View(lst); } public ActionResult Delete(int? i) { var st = lst.Find(c=>c.Id==i); lst.Remove(st); return View("Index",lst); } 

这是我的观点:

  @foreach (var item in Model) {  } 

您可以使用Session。

例如,将此属性添加到控制器:

 public List Students { get { if(Session["Students"] == null) { Session["Students"] = new List { new Student {Id = 1, Name = "Name1"}, new Student{Id = 2 , Name = "Name2"}, new Student{Id = 3 , Name = "Name3"}, }; } return Session["Students"] as List; } set { Session["Students"] = value; } } 

并在删除操作中使用它:

 public ActionResult Delete(int? i) { var st = Students.Find(c=>c.Id==i); Students.Remove(st); return View("Index",lst); } 
ID Name
@item.Id @item.Name @Html.ActionLink("Delete","Delete",new{i = item.Id})