Search code examples
c#asp.net-mvc-5viewbag

MVC-5 After editing a value, is not displaying the results in other view


Hi I'm new here and English is not my first language, so forgive me for any grammar or spelling mistake.

The problem I'm currently having is when I edit an object and try to display the values in other view. I've already checked that the object is been save in the database, but when I try to display its value in and other view, it doesn't update. I have to open and close the app to be updated.

This is the controller code

Edit(int? id)
{
    ...
    Teacher teacher = db.Teacher.Find(id);
    return View(model);
}

[HttpPost]
Edit(Teacher teacher)
{
    var _teacher = db.Teacher.Find(teacher.id);
    db.Entry(_teacher ).CurrentValues.SetValues(Teacher);
    db.SaveChanges();
    return redirecToAction("DisplayStudent", new {id=Teacher.studentId});
}

DisplayStudent(int? id)
{
    var student = db.Studen.Find(id);
    ViewBag.Teachers = db.Teacher.Where(model => model.studentId ==id).ToList();
    return View(student);
}

This the view

@model Student

@{
    List<Teacher> Teachers = (List<Model>)ViewBag.Teachers;
}

....

@foreach(var teacher in Teachers)
{
    <p>@teacher.name<p>
    <p>@teacher.lastName<p>
}

Solution

  • I've already solve the problem, the database wasn't been updated.

    All I did was put in DisplayStudent(int? id)

    DisplayStudent(int? id)
    {
        db.dispose();
        db = new dbEntities();
        var student = db.Studen.Find(id);
        ViewBag.Teachers = db.Teacher.Where(model => model.studentId ==id).ToList();
        return View(student);
    }