我在 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");
}
更新完成后,该方法会正确记录更改。我尝试编辑该元素而不是删除它,但没有成功。
如何解决这个问题?
最佳答案
不要在 Edit 方法结束时重定向用户,而是传回包含更新的学生列表的 View 。像这样:
而不是:
return RedirectToAction("Index");
用途:
return View("Index", studentList);
(其中“Index”是您要显示的 View 的名称。)
调用RedirectToAction
会重新加载类并重新初始化studentList
,因此它将显示原始列表,而不是显示更新后的列表。
关于C# IList更新问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52526810/