C# IList更新问题

标签 c# asp.net asp.net-mvc-4

我在 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/

相关文章:

c# - 如何更改此设计以避免沮丧?

c# - 从几个 UserControl 在 WPF 窗口中动态更改内容

c# - 为什么 mdf 文件没有出现在 App_Data 文件夹中?

c# - 如何对 Service Fabric 应用程序进行版本控制和分离?

c# - 如何将 TabControl 绑定(bind)到 ViewModel 集合?

javascript - 回发后在 TextBox 中设置焦点

css - 更改表 ASP.NET 中复选框列表的 css 样式

asp.net - Payu 的付款 api 验证无法正常工作

c# - 如何在表单中呈现列表项?

asp.net-mvc - Knockoutjs 可编辑网格