Part 24 Deleting database records using post request in mvc04:33

  • 0
Published on October 26, 2017

In this video we will discuss,
1. Deleting database records using POST request
2. Showing the client side javascript confirmation dialog box before deleting

Please watch Part 23, before proceeding.

Step 1: Mark “Delete” action method in “Employee” controller with [HttpPost] attribute. With this change, the “Delete” method will no longer respond to “GET” request. At this point, if we run the application and click on “Delete” link on the “Index” view, we get an error stating – “The resource cannot be found”
[HttpPost]
public ActionResult Delete(int id)
{
EmployeeBusinessLayer employeeBusinessLayer =
new EmployeeBusinessLayer();
employeeBusinessLayer.DeleteEmployee(id);
return RedirectToAction(“Index”);
}

Step 2: In “Index.cshtml”
REPLACE THE FOLLOWING CODE
@foreach (var item in Model) {
[tr]
[td]
@Html.DisplayFor(modelItem =] item.Name)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.Gender)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.City)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.DateOfBirth)
[/td]
[td]
@Html.ActionLink(“Edit”, “Edit”, new { id=item.ID }) |
@Html.ActionLink(“Details”, “Details”, new { id=item.ID }) |
@Html.ActionLink(“Delete”, “Delete”, new { id=item.ID })
[/td]
[/tr]
}

WITH
@foreach (var item in Model)
{
using (Html.BeginForm(“Delete”, “Employee”, new { id = item.ID }))
{
[tr]
[td]
@Html.DisplayFor(modelItem =] item.Name)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.Gender)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.City)
[/td]
[td]
@Html.DisplayFor(modelItem =] item.DateOfBirth)
[/td]
[td]
@Html.ActionLink(“Edit”, “Edit”, new { id = item.ID }) |
[input type=”submit” value=”Delete” /]
[/td]
[/tr]
}
}

Notice that, we are using “Html.BeginForm()” html helper to generate a form tag.

Step 3: To include client-side confirmation, before the data can be deleted, add the “onclick” attribute to “Delete” button as shown below.
[input type=”submit” value=”Delete” onclick=”return confirm(‘Are you sure you want to delete record with ID = @item.ID’);” /]

Text version of the video

Slides

All ASP .NET MVC Text Articles

All ASP .NET MVC Slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

Enjoyed this video?
"No Thanks. Please Close This Box!"