user5032790
user5032790

Reputation:

Remove an item from a List ASP.NET MVC

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

And here is my View:

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

Upvotes: 2

Views: 27728

Answers (1)

Vano Maisuradze
Vano Maisuradze

Reputation: 5909

You can use Session for that.

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

Upvotes: 2

Related Questions