0

A list of in-controller students gets reset after I edit it within my Post method.

I debugged to make sure the edit method was actually changing the list and it was. As soon as I RedirectToAction("Index") the list of students goes back to the original.

    public class StudentController : Controller
    {
        private List<Student> students = new List<Student>()
            {
                new Student() { Id = 0, Name = "John", Age = 18 },
                new Student() { Id = 1, Name = "Steve", Age = 21 },
                new Student() { Id = 2, Name = "Bill", Age = 25 },
                new Student() { Id = 3, Name = "Ram", Age = 20 },
                new Student() { Id = 4, Name = "Ron", Age = 31 },
                new Student() { Id = 5, Name = "Chris", Age = 17 },
                new Student() { Id = 6, Name = "Rob", Age = 19 },
            };

        public IActionResult Index()
        {
            return View(students);
        }

        public IActionResult Edit(int id)
        {
            Student std = students.Where(s => s.Id == id).FirstOrDefault();
            return View(std);
        }

        [HttpPost]
        public IActionResult Edit(Student std)
        {
            students[std.Id] = std;
            return RedirectToAction("Index");
        }
    }
Loen10
  • 71
  • 6
  • 1
    The list you're using for backing data is reconstructed every time the controller is constructed, and the controller is constructed every time there is a new request. You could make it static, or you could implement a mock repository. – Jonathon Chase Jul 19 '19 at 20:23
  • Making it static works for now. Thanks. – Loen10 Jul 19 '19 at 20:33
  • 2
    Someone should warn you, OP, that using `static` in a web site is usually a pretty bad idea. The same data will be available to all users, which is disastrous in most scenarios. For alternatives, see [ASP.Net MVC and state - how to keep state between requests](https://stackoverflow.com/questions/10756140/asp-net-mvc-and-state-how-to-keep-state-between-requests). – John Wu Jul 20 '19 at 00:20
  • I understand, I will use a real database with the real website. For testing purposes I made it static. – Loen10 Jul 21 '19 at 03:33

0 Answers0