HI WELCOME TO SIRIS

Part 24 - Deleting database records using post request in mvc

Leave a Comment
we will discuss 
1. Deleting database records using POST request
2. Showing the client side javascript confirmation dialog box before deleting

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');" />

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.