从列表ASP.NET MVC

时间:2016-04-10 14:11:44

标签: c# asp.net-mvc

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

List<Student> lst;
public HomeController()
{
   lst = new List<Student>
   {
       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);
}

这是我的观点:

<table style="border: 1px solid silver">
<thead>
<tr>
    <th>ID</th>
    <th>Name</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
    <tr>
        <td>
            @item.Id
        </td>
        <td>
            @item.Name
        </td>
        <td>
            @Html.ActionLink("Delete","Delete",new{i = item.Id})
        </td>
    </tr>
}
</tbody>

1 个答案:

答案 0 :(得分:3)

您可以使用Session。

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

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

并在删除操作中使用它:

public ActionResult Delete(int? i)
{
     var st = Students.Find(c=>c.Id==i);
     Students.Remove(st);
     return View("Index",lst);
}