1. Add a delete method at businessLayer project
public void DeleteEmployee(int id)
{
string connectionString = ConfigurationManager.ConnectionStrings["employeeDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("spDeleteEMployee", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramId = new SqlParameter();
paramId.ParameterName = "@Id";
paramId.Value = id;
cmd.Parameters.Add(paramId);
con.Open();
cmd.ExecuteNonQuery();
}
}
2. Add a controller method at EmployeeController.cs
public ActionResult Delete(int id)
{
EmployeeBusinessLayer employeeBusinesslayer = new EmployeeBusinessLayer();
employeeBusinesslayer.DeleteEmployee(id);
return RedirectToAction("Index");
}
** Using GET method to delete a record is not required as it could be used a bad way.
3. Therefore, recommend using POST method
[HttpPost] <-- add this part on the controller method
4. add some javascript to check before deleting
@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" onclick="return confirm('Are you sure you want to delete record with ID = @item.Id');"/>
</td>
</tr>
}
}