Is good practice to resist the temptation of doing the delete action in the get request. It would be a huge security error, it has to be done always in the post method.
// GET: Student/Delete/5
public ActionResult Delete(int? id)
{
// it good practice to consider that things could go wrong so,it is wise to have a validation in the controller
if (id == null)
{
// returns a bad request
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// It finds the Student to be deleted.
Student student = db.Students.Find(id);
if (student == null)
{
// if doesn't found returns 404
return HttpNotFound();
}
// Returns the Student data to show the details of what will be deleted.
return View(student);
}
// POST: Student/Delete/5
[HttpPost]
//Represents an attribute that is used for the name of an action.
[ActionName("Delete")]
//used to To protect from overposting attacks more details see http://stackoverflow.com/documentation/asp.net-mvc/1997/html-antiforgerytoke
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
try
{
// Finds the student
Student student = db.Students.Find(id);
// Try to remove it
db.Students.Remove(student);
// Save the changes
db.SaveChanges();
}
catch
{
//Log the error add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
// Returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action, in this case the index action.
return RedirectToAction("Index");
}