C#IList更新问题

问题描述 投票:2回答:1

我在C#中使用IList时遇到了问题。

我有我的类中的列表,以及一个应该更新它的方法。但是,一旦我需要显示列表或再次更新它,我会得到原始列表而不是更新列表。

 IList<Student> studentList = new List<Student>{
                        new Student() { StudentId = 1, StudentName = "John", Age = 18 } ,
                        new Student() { StudentId = 2, StudentName = "Steve",  Age = 21 } ,
                        new Student() { StudentId = 3, StudentName = "Bill",  Age = 25 } ,
                        new Student() { StudentId = 4, StudentName = "Ram" , Age = 20 } ,
                        new Student() { StudentId = 5, StudentName = "Ron" , Age = 31 } ,
                        new Student() { StudentId = 6, StudentName = "Chris" , Age = 17 } ,
                        new Student() { StudentId = 7, StudentName = "Rob" , Age = 19 }
                    };

    // GET: Student
    public ActionResult Index()
    {
        return View(studentList);
    }
[HttpPost]
public ActionResult Edit(Student std)
{
    var name = std.StudentName;
    var age = std.Age;
    var id = std.StudentId;

    Student stud = new Student();
    stud.Age = age;
    stud.StudentId = id;
    stud.StudentName = name;

    studentList.RemoveAt(id-1);
    Debug.WriteLine(id);

    return RedirectToAction("Index");
}

更新完成后,该方法会正确记录更改。我试过编辑元素而不是删除它,但没有用。

我该如何解决这个问题?

c# asp.net asp.net-mvc-4
1个回答
3
投票

不要在Edit方法的末尾重定向用户,而是使用更新的学生列表传回View。像这样:

代替:

return RedirectToAction("Index");

使用:

return View("Index", studentList); 

(其中'Index'是您要显示的视图的名称。)

调用RedirectToAction重新加载类并重新初始化studentList,因此它不会显示更新列表,而是显示原始列表。

© www.soinside.com 2019 - 2024. All rights reserved.