C# – returning confirmation message on same page

asp.net-mvcc

How can I display a message on the same browser after inserting a student? Currently I am using return content which navigates me to a new page, but I want to display the message on same page and stay on the same page:

Index Controller:

    public ActionResult Index()
    {
        return View(_repository.ListAll().OrderByDescending(s => s.StudentID));

    }

Controller Action:

    public ActionResult RemoveStudent(int id)
    {

        StudentDataContext student= new StudentDataContext();

        var std = student.Students.Single(s => s.StudentID == id);
        student.Students.DeleteOnSubmit(std);
        student.SubmitChanges();
        return Content("Student " + std.StudentId.ToString() + " Removed");

    }

Thanks in advance

Best Answer

Return your view, and you can store the message in a model or in your TempData.

public ActionResult RemoveStudent(int id)
{
    StudentDataContext student= new StudentDataContext();

    var std = student.Students.Single(s => s.StudentID == id);
    student.Students.DeleteOnSubmit(std);
    student.SubmitChanges();

    TempData["Message"] = "Student " + std.StudentId.ToString() + " Removed";
    return RedirectToAction("Index");
}

In your view, you can check if TempData["Message"] is not null and display it.

Related Topic