从列表中ASP.NET MVC中删除项目 [英] Remove an item from a List ASP.NET MVC

查看:104
本文介绍了从列表中ASP.NET MVC中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学生的List。我每次点击删除链接就可以从列表中删除所选的学生,但如果我重复一下另一个记录的删除链接我的名单返回到默认初始化,然后删除新的记录就完成了。我知道我的问题是,因为我初始化我在控制器的构造函数列表。所以,我应该在哪里初始化我的名单中不回传重新初始化?

I have a List of Student. Every time I click on the Delete link it removes the selected student from the list but if I repeat clicking the delete link for another record my list returns back to default initialize and then delete the new record is done. I know my problem is because I initialized my list in the controller's constructor. So where should I initialize my list that doesn't be reinitialized in postbacks?

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>

推荐答案

您可以使用会话了点。

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

For example, add this property to controller:

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;
   }
}

和在你的删除操作使用它:

and use it in your Delete action:

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

这篇关于从列表中ASP.NET MVC中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆